lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
mit
9f1b6301200aca9ea889c969930d999df74a0bad
0
douxiaozhao/java-memcached-client,resrugam/java-memcached-client,Agilefant/spymemcached,HubSpot/java-memcached-client,couchbase/spymemcached,douxiaozhao/java-memcached-client,tootedom/spymemcached-1,Agilefant/spymemcached,tootedom/spymemcached-1,tootedom/spymemcached,dustin/java-memcached-client,1and1/java-memcached-client,Agilefant/spymemcached,tootedom/spymemcached,dustin/java-memcached-client,couchbase/spymemcached,resrugam/java-memcached-client,douxiaozhao/java-memcached-client,HubSpot/java-memcached-client,resrugam/java-memcached-client,tootedom/spymemcached-1,couchbase/spymemcached,HubSpot/java-memcached-client,dustin/java-memcached-client,tootedom/spymemcached
package net.spy.memcached; import java.nio.ByteBuffer; import net.spy.memcached.ops.Operation; import net.spy.memcached.ops.OperationCallback; import net.spy.memcached.ops.OperationStatus; import net.spy.memcached.protocol.ascii.ExtensibleOperationImpl; /** * * @author Matt Ingenthron <[email protected]> */ public class TimeoutNowriteTest extends ClientBaseCase { @Override protected void tearDown() throws Exception { // override teardown to avoid the flush phase client.shutdown(); } @Override protected void initClient() throws Exception { client=new MemcachedClient(new DefaultConnectionFactory() { @Override public long getOperationTimeout() { return 1000; // 1 sec } @Override public FailureMode getFailureMode() { return FailureMode.Retry; }}, AddrUtil.getAddresses("127.0.0.1:11211")); } private void tryTimeout(String name, Runnable r) { try { r.run(); fail("Expected timeout in " + name); } catch(OperationTimeoutException e) { // pass } } public void testTimeoutDontwrite() { Operation op = new ExtensibleOperationImpl(new OperationCallback(){ public void complete() { System.err.println("Complete."); } public void receivedStatus(OperationStatus s) { System.err.println("Received a line."); }}) { @Override public void handleLine(String line) { System.out.println("Woo! A line!"); } @Override public void initialize() { setBuffer(ByteBuffer.wrap("garbage\r\n".getBytes())); } }; try { Thread.sleep(1100); } catch (InterruptedException ex) { System.err.println("Interrupted when sleeping for timeout nowrite"); } client.addOp("x", op); System.err.println("Operation attempted:"); System.err.println(op); System.err.println("Trying to get:"); try { byte[] retVal = (byte[])client.get("x"); String retValString = new String(); System.err.println(retValString); } catch (net.spy.memcached.OperationTimeoutException ex) { System.err.println("Timed out successfully: " + ex.getMessage()); } System.err.println("Op timed out is " + op.isTimedOut()); assert(op.isTimedOut() == true); } }
src/test/java/net/spy/memcached/TimeoutNowriteTest.java
package net.spy.memcached; import java.util.logging.Level; import java.util.logging.Logger; import net.spy.memcached.ops.Operation; import net.spy.memcached.ops.OperationCallback; import net.spy.memcached.ops.OperationStatus; import net.spy.memcached.protocol.ascii.ExtensibleOperationImpl; import java.nio.ByteBuffer; /** * * @author Matt Ingenthron <[email protected]> */ public class TimeoutNowriteTest extends ClientBaseCase { @Override protected void tearDown() throws Exception { // override teardown to avoid the flush phase client.shutdown(); } @Override protected void initClient() throws Exception { client=new MemcachedClient(new DefaultConnectionFactory() { @Override public long getOperationTimeout() { return 1000; // 1 sec } @Override public FailureMode getFailureMode() { return FailureMode.Retry; }}, AddrUtil.getAddresses("127.0.0.1:11211")); } private void tryTimeout(String name, Runnable r) { try { r.run(); fail("Expected timeout in " + name); } catch(OperationTimeoutException e) { // pass } } public void testTimeoutDontwrite() { Operation op = new ExtensibleOperationImpl(new OperationCallback(){ public void complete() { System.err.println("Complete."); } public void receivedStatus(OperationStatus s) { System.err.println("Received a line."); }}) { @Override public void handleLine(String line) { System.out.println("Woo! A line!"); } @Override public void initialize() { setBuffer(ByteBuffer.wrap("garbage\r\n".getBytes())); } }; try { Thread.sleep(1100); } catch (InterruptedException ex) { System.err.println("Interrupted when sleeping for timeout nowrite"); } client.addOp("x", op); System.err.println("Operation attempted:"); System.err.println(op); System.err.println("Trying to get:"); try { byte[] retVal = (byte[])client.get("x"); String retValString = new String(); System.err.println(retValString); } catch (net.spy.memcached.OperationTimeoutException ex) { System.err.println("Timed out successfully: " + ex.getMessage()); } System.err.println("Op timed out is " + op.isTimedOut()); assert(op.isTimedOut() == true); } }
Some import cleanups. Change-Id: I54bdc264566684208e5273ce51d56f38d14be852 Reviewed-on: http://review.membase.org/4231 Tested-by: Matt Ingenthron <[email protected]> Reviewed-by: Matt Ingenthron <[email protected]>
src/test/java/net/spy/memcached/TimeoutNowriteTest.java
Some import cleanups.
<ide><path>rc/test/java/net/spy/memcached/TimeoutNowriteTest.java <ide> package net.spy.memcached; <ide> <del>import java.util.logging.Level; <del>import java.util.logging.Logger; <add>import java.nio.ByteBuffer; <add> <ide> import net.spy.memcached.ops.Operation; <ide> import net.spy.memcached.ops.OperationCallback; <ide> import net.spy.memcached.ops.OperationStatus; <ide> import net.spy.memcached.protocol.ascii.ExtensibleOperationImpl; <del>import java.nio.ByteBuffer; <ide> <ide> /** <ide> *
Java
apache-2.0
78394e8bae186c5dcaef6ffffdf42910fa64334c
0
tombolaltd/cordova-plugin-inappbrowser,tombolaltd/cordova-plugin-inappbrowser,tombolaltd/cordova-plugin-inappbrowser
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.cordova.inappbrowser; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.provider.Browser; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.InputType; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.HttpAuthHandler; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import org.apache.cordova.CallbackContext; import org.apache.cordova.Config; import org.apache.cordova.CordovaArgs; import org.apache.cordova.CordovaHttpAuthHandler; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.LOG; import org.apache.cordova.PluginManager; import org.apache.cordova.PluginResult; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.StringTokenizer; @SuppressLint("SetJavaScriptEnabled") public class InAppBrowser extends CordovaPlugin { private static final String NULL = "null"; protected static final String LOG_TAG = "InAppBrowser"; private static final String SELF = "_self"; private static final String SYSTEM = "_system"; private static final String EXIT_EVENT = "exit"; private static final String LOCATION = "location"; private static final String ZOOM = "zoom"; private static final String HIDDEN = "hidden"; private static final String LOAD_START_EVENT = "loadstart"; private static final String LOAD_STOP_EVENT = "loadstop"; private static final String LOAD_ERROR_EVENT = "loaderror"; private static final String CLEAR_ALL_CACHE = "clearcache"; private static final String CLEAR_SESSION_CACHE = "clearsessioncache"; private static final String HARDWARE_BACK_BUTTON = "hardwareback"; private static final String MEDIA_PLAYBACK_REQUIRES_USER_ACTION = "mediaPlaybackRequiresUserAction"; private static final String SHOULD_PAUSE = "shouldPauseOnSuspend"; private InAppBrowserDialog dialog; private WebView inAppWebView; private EditText edittext; private CallbackContext callbackContext; private boolean showLocationBar = true; private boolean showZoomControls = true; private boolean openWindowHidden = false; private boolean clearAllCache = false; private boolean clearSessionCache = false; private boolean hadwareBackButton = true; private boolean mediaPlaybackRequiresUserGesture = false; private boolean shouldPauseInAppBrowser = false; /** * Executes the request and returns PluginResult. * * @param action the action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext the callbackContext used when calling back into JavaScript. * @return A PluginResult object with a status and message. */ public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException { if (action.equals("open")) { this.callbackContext = callbackContext; final String url = args.getString(0); String t = args.optString(1); if (t == null || t.equals("") || t.equals(NULL)) { t = SELF; } final String target = t; final HashMap<String, Boolean> features = parseFeature(args.optString(2)); LOG.d(LOG_TAG, "target = " + target); this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { String result = ""; // SELF if (SELF.equals(target)) { LOG.d(LOG_TAG, "in self"); /* This code exists for compatibility between 3.x and 4.x versions of Cordova. * Previously the Config class had a static method, isUrlWhitelisted(). That * responsibility has been moved to the plugins, with an aggregating method in * PluginManager. */ Boolean shouldAllowNavigation = shouldAllowNavigation(url); // load in webview if (Boolean.TRUE.equals(shouldAllowNavigation)) { LOG.d(LOG_TAG, "loading in webview"); webView.loadUrl(url); } //Load the dialer else if (url.startsWith(WebView.SCHEME_TEL)) { try { LOG.d(LOG_TAG, "loading in dialer"); Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString()); } } // load in InAppBrowser else { LOG.d(LOG_TAG, "loading in InAppBrowser"); result = showWebPage(url, features); } } // SYSTEM else if (SYSTEM.equals(target)) { LOG.d(LOG_TAG, "in system"); result = openExternal(url); } // BLANK - or anything else else { LOG.d(LOG_TAG, "in blank"); result = showWebPage(url, features); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } }); } else if (action.equals("close")) { closeDialog(); } else if (action.equals("injectScriptCode")) { String jsWrapper = null; if (args.getBoolean(1)) { jsWrapper = String.format("(function(){prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')})()", callbackContext.getCallbackId()); } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectScriptFile")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectStyleCode")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectStyleFile")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("show")) { showDialogue(); } else if (action.equals("hide")) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if(dialog != null) { dialog.hide(); } } }); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); pluginResult.setKeepCallback(true); this.callbackContext.sendPluginResult(pluginResult); } else if (action.equals("reveal")) { if(args == null){ showDialogue(); } else { showDialogue(); } // String jsWrapper = String.format("(function(){" + // "prompt(JSON.stringify([eval(%s)]))" + // "})()", args ); // injectDeferredObject("console.log('YAY**************');", jsWrapper); String url = args.getString(0); // if (url == null || url.equals("") || url.equals(NULL)) { // // } // else { // Boolean shouldAllowNavigation = shouldAllowNavigation(url); // if (inAppWebView != null && shouldAllowNavigation) { // navigate(url); // showDialogue(); // } // } } else { return false; } return true; } public void showDialogue() { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if(dialog != null) { dialog.show(); } } }); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); pluginResult.setKeepCallback(true); this.callbackContext.sendPluginResult(pluginResult); } public Boolean shouldAllowNavigation(String url) { Boolean shouldAllowNavigation = null; if (url.startsWith("javascript:")) { shouldAllowNavigation = true; } if (shouldAllowNavigation == null) { try { Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class); shouldAllowNavigation = (Boolean)iuw.invoke(null, url); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } if (shouldAllowNavigation == null) { try { Method gpm = webView.getClass().getMethod("getPluginManager"); PluginManager pm = (PluginManager)gpm.invoke(webView); Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class); shouldAllowNavigation = (Boolean)san.invoke(pm, url); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } return shouldAllowNavigation; } /** * Called when the view navigates. */ @Override public void onReset() { closeDialog(); } /** * Called when the system is about to start resuming a previous activity. */ @Override public void onPause(boolean multitasking) { if (shouldPauseInAppBrowser) { inAppWebView.onPause(); } } /** * Called when the activity will start interacting with the user. */ @Override public void onResume(boolean multitasking) { if (shouldPauseInAppBrowser) { inAppWebView.onResume(); } } /** * Called by AccelBroker when listener is to be shut down. * Stop listener. */ public void onDestroy() { closeDialog(); } /** * Inject an object (script or style) into the InAppBrowser WebView. * * This is a helper method for the inject{Script|Style}{Code|File} API calls, which * provides a consistent method for injecting JavaScript code into the document. * * If a wrapper string is supplied, then the source string will be JSON-encoded (adding * quotes) and wrapped using string formatting. (The wrapper string should have a single * '%s' marker) * * @param source The source object (filename or script/style text) to inject into * the document. * @param jsWrapper A JavaScript string to wrap the source string in, so that the object * is properly injected, or null if the source string is JavaScript text * which should be executed directly. */ private void injectDeferredObject(String source, String jsWrapper) { String scriptToInject; if (jsWrapper != null) { org.json.JSONArray jsonEsc = new org.json.JSONArray(); jsonEsc.put(source); String jsonRepr = jsonEsc.toString(); String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1); scriptToInject = String.format(jsWrapper, jsonSourceString); } else { scriptToInject = source; } final String finalScriptToInject = scriptToInject; this.cordova.getActivity().runOnUiThread(new Runnable() { @SuppressLint("NewApi") @Override public void run() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { // This action will have the side-effect of blurring the currently focused element inAppWebView.loadUrl("javascript:" + finalScriptToInject); } else { inAppWebView.evaluateJavascript(finalScriptToInject, null); } } }); } /** * Put the list of features into a hash map * * @param optString * @return */ private HashMap<String, Boolean> parseFeature(String optString) { if (optString.equals(NULL)) { return null; } else { HashMap<String, Boolean> map = new HashMap<String, Boolean>(); StringTokenizer features = new StringTokenizer(optString, ","); StringTokenizer option; while(features.hasMoreElements()) { option = new StringTokenizer(features.nextToken(), "="); if (option.hasMoreElements()) { String key = option.nextToken(); Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE; map.put(key, value); } } return map; } } /** * Display a new browser with the specified URL. * * @param url the url to load. * @return "" if ok, or error message. */ public String openExternal(String url) { try { Intent intent = null; intent = new Intent(Intent.ACTION_VIEW); // Omitting the MIME type for file: URLs causes "No Activity found to handle Intent". // Adding the MIME type to http: URLs causes them to not be handled by the downloader. Uri uri = Uri.parse(url); if ("file".equals(uri.getScheme())) { intent.setDataAndType(uri, webView.getResourceApi().getMimeType(uri)); } else { intent.setData(uri); } intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName()); this.cordova.getActivity().startActivity(intent); return ""; } catch (android.content.ActivityNotFoundException e) { LOG.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString()); return e.toString(); } } /** * Closes the dialog */ public void closeDialog() { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { final WebView childView = inAppWebView; // The JS protects against multiple calls, so this should happen only when // closeDialog() is called by other native code. if (childView == null) { return; } childView.setWebViewClient(new WebViewClient() { // NB: wait for about:blank before dismissing public void onPageFinished(WebView view, String url) { if (dialog != null) { dialog.dismiss(); dialog = null; } } }); // NB: From SDK 19: "If you call methods on WebView from any thread // other than your app's UI thread, it can cause unexpected results." // http://developer.android.com/guide/webapps/migrating.html#Threads childView.loadUrl("about:blank"); childView.destroy(); try { JSONObject obj = new JSONObject(); obj.put("type", EXIT_EVENT); sendUpdate(obj, false); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } }); } /** * Checks to see if it is possible to go back one page in history, then does so. */ public void goBack() { if (this.inAppWebView.canGoBack()) { this.inAppWebView.goBack(); } } /** * Can the web browser go back? * @return boolean */ public boolean canGoBack() { return this.inAppWebView.canGoBack(); } /** * Has the user set the hardware back button to go back * @return boolean */ public boolean hardwareBack() { return hadwareBackButton; } /** * Checks to see if it is possible to go forward one page in history, then does so. */ private void goForward() { if (this.inAppWebView.canGoForward()) { this.inAppWebView.goForward(); } } /** * Navigate to the new page * * @param url to load */ private void navigate(String url) { InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0); if (!url.startsWith("http") && !url.startsWith("file:")) { this.inAppWebView.loadUrl("http://" + url); } else { this.inAppWebView.loadUrl(url); } this.inAppWebView.requestFocus(); } /** * Should we show the location bar? * * @return boolean */ private boolean getShowLocationBar() { return this.showLocationBar; } private InAppBrowser getInAppBrowser(){ return this; } /** * Display a new browser with the specified URL. * * @param url the url to load. * @param features jsonObject */ public String showWebPage(final String url, HashMap<String, Boolean> features) { // Determine if we should hide the location bar. showLocationBar = true; showZoomControls = true; openWindowHidden = false; mediaPlaybackRequiresUserGesture = false; if (features != null) { Boolean show = features.get(LOCATION); if (show != null) { showLocationBar = show.booleanValue(); } Boolean zoom = features.get(ZOOM); if (zoom != null) { showZoomControls = zoom.booleanValue(); } Boolean hidden = features.get(HIDDEN); if (hidden != null) { openWindowHidden = hidden.booleanValue(); } Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON); if (hardwareBack != null) { hadwareBackButton = hardwareBack.booleanValue(); } Boolean mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION); if (mediaPlayback != null) { mediaPlaybackRequiresUserGesture = mediaPlayback.booleanValue(); } Boolean cache = features.get(CLEAR_ALL_CACHE); if (cache != null) { clearAllCache = cache.booleanValue(); } else { cache = features.get(CLEAR_SESSION_CACHE); if (cache != null) { clearSessionCache = cache.booleanValue(); } } Boolean shouldPause = features.get(SHOULD_PAUSE); if (shouldPause != null) { shouldPauseInAppBrowser = shouldPause.booleanValue(); } } final CordovaWebView thatWebView = this.webView; // Create dialog in new thread Runnable runnable = new Runnable() { /** * Convert our DIP units to Pixels * * @return int */ private int dpToPixels(int dipValue) { int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, (float) dipValue, cordova.getActivity().getResources().getDisplayMetrics() ); return value; } @SuppressLint("NewApi") public void run() { // CB-6702 InAppBrowser hangs when opening more than one instance if (dialog != null) { dialog.dismiss(); }; // Let's create the main dialog dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar); dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setInAppBroswer(getInAppBrowser()); // Main container layout LinearLayout main = new LinearLayout(cordova.getActivity()); main.setOrientation(LinearLayout.VERTICAL); // Toolbar layout RelativeLayout toolbar = new RelativeLayout(cordova.getActivity()); //Please, no more black! toolbar.setBackgroundColor(android.graphics.Color.LTGRAY); toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44))); toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2)); toolbar.setHorizontalGravity(Gravity.LEFT); toolbar.setVerticalGravity(Gravity.TOP); // Action Button Container layout RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity()); actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); actionButtonContainer.setHorizontalGravity(Gravity.LEFT); actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); actionButtonContainer.setId(Integer.valueOf(1)); // Back button ImageButton back = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT); back.setLayoutParams(backLayoutParams); back.setContentDescription("Back Button"); back.setId(Integer.valueOf(2)); Resources activityRes = cordova.getActivity().getResources(); int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName()); Drawable backIcon = activityRes.getDrawable(backResId); if (Build.VERSION.SDK_INT >= 16) back.setBackground(null); else back.setBackgroundDrawable(null); back.setImageDrawable(backIcon); back.setScaleType(ImageView.ScaleType.FIT_CENTER); back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10)); if (Build.VERSION.SDK_INT >= 16) back.getAdjustViewBounds(); back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goBack(); } }); // Forward button ImageButton forward = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2); forward.setLayoutParams(forwardLayoutParams); forward.setContentDescription("Forward Button"); forward.setId(Integer.valueOf(3)); int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName()); Drawable fwdIcon = activityRes.getDrawable(fwdResId); if (Build.VERSION.SDK_INT >= 16) forward.setBackground(null); else forward.setBackgroundDrawable(null); forward.setImageDrawable(fwdIcon); forward.setScaleType(ImageView.ScaleType.FIT_CENTER); forward.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10)); if (Build.VERSION.SDK_INT >= 16) forward.getAdjustViewBounds(); forward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goForward(); } }); // Edit Text Box edittext = new EditText(cordova.getActivity()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setId(Integer.valueOf(4)); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { navigate(edittext.getText().toString()); return true; } return false; } }); // Close/Done button ImageButton close = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); close.setLayoutParams(closeLayoutParams); forward.setContentDescription("Close Button"); close.setId(Integer.valueOf(5)); int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName()); Drawable closeIcon = activityRes.getDrawable(closeResId); if (Build.VERSION.SDK_INT >= 16) close.setBackground(null); else close.setBackgroundDrawable(null); close.setImageDrawable(closeIcon); close.setScaleType(ImageView.ScaleType.FIT_CENTER); back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10)); if (Build.VERSION.SDK_INT >= 16) close.getAdjustViewBounds(); close.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeDialog(); } }); // WebView inAppWebView = new WebView(cordova.getActivity()); inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); inAppWebView.setId(Integer.valueOf(6)); inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView)); WebViewClient client = new InAppBrowserClient(thatWebView, edittext); inAppWebView.setWebViewClient(client); WebSettings settings = inAppWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(showZoomControls); settings.setPluginState(android.webkit.WebSettings.PluginState.ON); if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture); } String overrideUserAgent = preferences.getString("OverrideUserAgent", null); String appendUserAgent = preferences.getString("AppendUserAgent", null); if (overrideUserAgent != null) { settings.setUserAgentString(overrideUserAgent); } if (appendUserAgent != null) { settings.setUserAgentString(settings.getUserAgentString() + appendUserAgent); } //Toggle whether this is enabled or not! Bundle appSettings = cordova.getActivity().getIntent().getExtras(); boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true); if (enableDatabase) { String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); settings.setDatabaseEnabled(true); } settings.setDomStorageEnabled(true); if (clearAllCache) { CookieManager.getInstance().removeAllCookie(); } else if (clearSessionCache) { CookieManager.getInstance().removeSessionCookie(); } inAppWebView.loadUrl(url); inAppWebView.setId(Integer.valueOf(6)); inAppWebView.getSettings().setLoadWithOverviewMode(true); inAppWebView.getSettings().setUseWideViewPort(true); inAppWebView.requestFocus(); inAppWebView.requestFocusFromTouch(); // Add the back and forward buttons to our action button container layout actionButtonContainer.addView(back); actionButtonContainer.addView(forward); // Add the views to our toolbar toolbar.addView(actionButtonContainer); toolbar.addView(edittext); toolbar.addView(close); // Don't add the toolbar if its been disabled if (getShowLocationBar()) { // Add our toolbar to our main view/layout main.addView(toolbar); } // Add our webview to our main view/layout main.addView(inAppWebView); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); // the goal of openhidden is to load the url and not display it // Show() needs to be called to cause the URL to be loaded if(openWindowHidden) { dialog.hide(); } } }; this.cordova.getActivity().runOnUiThread(runnable); return ""; } /** * Create a new plugin success result and send it back to JavaScript * * @param obj a JSONObject contain event payload information */ private void sendUpdate(JSONObject obj, boolean keepCallback) { sendUpdate(obj, keepCallback, PluginResult.Status.OK); } /** * Create a new plugin result and send it back to JavaScript * * @param obj a JSONObject contain event payload information * @param status the status code to return to the JavaScript environment */ private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) { if (callbackContext != null) { PluginResult result = new PluginResult(status, obj); result.setKeepCallback(keepCallback); callbackContext.sendPluginResult(result); if (!keepCallback) { callbackContext = null; } } } /** * The webview client receives notifications about appView */ public class InAppBrowserClient extends WebViewClient { EditText edittext; CordovaWebView webView; /** * Constructor. * * @param webView * @param mEditText */ public InAppBrowserClient(CordovaWebView webView, EditText mEditText) { this.webView = webView; this.edittext = mEditText; } /** * Override the URL that should be loaded * * This handles a small subset of all the URIs that would be encountered. * * @param webView * @param url */ @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) { if (url.startsWith(WebView.SCHEME_TEL)) { try { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString()); } } else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:") || url.startsWith("intent:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString()); } } // If sms:5551212?body=This is the message else if (url.startsWith("sms:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); // Get address String address = null; int parmIndex = url.indexOf('?'); if (parmIndex == -1) { address = url.substring(4); } else { address = url.substring(4, parmIndex); // If body, then set sms body Uri uri = Uri.parse(url); String query = uri.getQuery(); if (query != null) { if (query.startsWith("body=")) { intent.putExtra("sms_body", query.substring(5)); } } } intent.setData(Uri.parse("sms:" + address)); intent.putExtra("address", address); intent.setType("vnd.android-dir/mms-sms"); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString()); } } return false; } /* * onPageStarted fires the LOAD_START_EVENT * * @param view * @param url * @param favicon */ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); String newloc = ""; if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) { newloc = url; } else { // Assume that everything is HTTP at this point, because if we don't specify, // it really should be. Complain loudly about this!!! LOG.e(LOG_TAG, "Possible Uncaught/Unknown URI"); newloc = "http://" + url; } // Update the UI if we haven't already if (!newloc.equals(edittext.getText().toString())) { edittext.setText(newloc); } try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_START_EVENT); obj.put("url", newloc); sendUpdate(obj, true); } catch (JSONException ex) { LOG.e(LOG_TAG, "URI passed in has caused a JSON error."); } } public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().flush(); } else { CookieSyncManager.getInstance().sync(); } try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_STOP_EVENT); obj.put("url", url); sendUpdate(obj, true); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_ERROR_EVENT); obj.put("url", failingUrl); obj.put("code", errorCode); obj.put("message", description); sendUpdate(obj, true, PluginResult.Status.ERROR); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } /** * On received http auth request. */ @Override public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { // Check if there is some plugin which can resolve this auth challenge PluginManager pluginManager = null; try { Method gpm = webView.getClass().getMethod("getPluginManager"); pluginManager = (PluginManager)gpm.invoke(webView); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } if (pluginManager == null) { try { Field pmf = webView.getClass().getField("pluginManager"); pluginManager = (PluginManager)pmf.get(webView); } catch (NoSuchFieldException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(webView, new CordovaHttpAuthHandler(handler), host, realm)) { return; } // By default handle 401 like we'd normally do! super.onReceivedHttpAuthRequest(view, handler, host, realm); } } }
src/android/InAppBrowser.java
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.cordova.inappbrowser; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.provider.Browser; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.InputType; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.HttpAuthHandler; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import org.apache.cordova.CallbackContext; import org.apache.cordova.Config; import org.apache.cordova.CordovaArgs; import org.apache.cordova.CordovaHttpAuthHandler; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.LOG; import org.apache.cordova.PluginManager; import org.apache.cordova.PluginResult; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.StringTokenizer; @SuppressLint("SetJavaScriptEnabled") public class InAppBrowser extends CordovaPlugin { private static final String NULL = "null"; protected static final String LOG_TAG = "InAppBrowser"; private static final String SELF = "_self"; private static final String SYSTEM = "_system"; private static final String EXIT_EVENT = "exit"; private static final String LOCATION = "location"; private static final String ZOOM = "zoom"; private static final String HIDDEN = "hidden"; private static final String LOAD_START_EVENT = "loadstart"; private static final String LOAD_STOP_EVENT = "loadstop"; private static final String LOAD_ERROR_EVENT = "loaderror"; private static final String CLEAR_ALL_CACHE = "clearcache"; private static final String CLEAR_SESSION_CACHE = "clearsessioncache"; private static final String HARDWARE_BACK_BUTTON = "hardwareback"; private static final String MEDIA_PLAYBACK_REQUIRES_USER_ACTION = "mediaPlaybackRequiresUserAction"; private static final String SHOULD_PAUSE = "shouldPauseOnSuspend"; private InAppBrowserDialog dialog; private WebView inAppWebView; private EditText edittext; private CallbackContext callbackContext; private boolean showLocationBar = true; private boolean showZoomControls = true; private boolean openWindowHidden = false; private boolean clearAllCache = false; private boolean clearSessionCache = false; private boolean hadwareBackButton = true; private boolean mediaPlaybackRequiresUserGesture = false; private boolean shouldPauseInAppBrowser = false; /** * Executes the request and returns PluginResult. * * @param action the action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext the callbackContext used when calling back into JavaScript. * @return A PluginResult object with a status and message. */ public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException { if (action.equals("open")) { this.callbackContext = callbackContext; final String url = args.getString(0); String t = args.optString(1); if (t == null || t.equals("") || t.equals(NULL)) { t = SELF; } final String target = t; final HashMap<String, Boolean> features = parseFeature(args.optString(2)); LOG.d(LOG_TAG, "target = " + target); this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { String result = ""; // SELF if (SELF.equals(target)) { LOG.d(LOG_TAG, "in self"); /* This code exists for compatibility between 3.x and 4.x versions of Cordova. * Previously the Config class had a static method, isUrlWhitelisted(). That * responsibility has been moved to the plugins, with an aggregating method in * PluginManager. */ Boolean shouldAllowNavigation = shouldAllowNavigation(url); // load in webview if (Boolean.TRUE.equals(shouldAllowNavigation)) { LOG.d(LOG_TAG, "loading in webview"); webView.loadUrl(url); } //Load the dialer else if (url.startsWith(WebView.SCHEME_TEL)) { try { LOG.d(LOG_TAG, "loading in dialer"); Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString()); } } // load in InAppBrowser else { LOG.d(LOG_TAG, "loading in InAppBrowser"); result = showWebPage(url, features); } } // SYSTEM else if (SYSTEM.equals(target)) { LOG.d(LOG_TAG, "in system"); result = openExternal(url); } // BLANK - or anything else else { LOG.d(LOG_TAG, "in blank"); result = showWebPage(url, features); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } }); } else if (action.equals("close")) { closeDialog(); } else if (action.equals("injectScriptCode")) { String jsWrapper = null; if (args.getBoolean(1)) { jsWrapper = String.format("(function(){prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')})()", callbackContext.getCallbackId()); } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectScriptFile")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectStyleCode")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectStyleFile")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("show")) { showDialogue(); } else if (action.equals("hide")) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if(dialog != null) { dialog.hide(); } } }); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); pluginResult.setKeepCallback(true); this.callbackContext.sendPluginResult(pluginResult); } else if (action.equals("reveal")) { if(args == null){ showDialogue(); } // String jsWrapper = String.format("(function(){" + // "prompt(JSON.stringify([eval(%s)]))" + // "})()", args ); // injectDeferredObject("console.log('YAY**************');", jsWrapper); String url = args.getString(0); if (url == null || url.equals("") || url.equals(NULL)) { } // else { // Boolean shouldAllowNavigation = shouldAllowNavigation(url); // if (inAppWebView != null && shouldAllowNavigation) { // navigate(url); // showDialogue(); // } // } } else { return false; } return true; } public void showDialogue() { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if(dialog != null) { dialog.show(); } } }); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); pluginResult.setKeepCallback(true); this.callbackContext.sendPluginResult(pluginResult); } public Boolean shouldAllowNavigation(String url) { Boolean shouldAllowNavigation = null; if (url.startsWith("javascript:")) { shouldAllowNavigation = true; } if (shouldAllowNavigation == null) { try { Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class); shouldAllowNavigation = (Boolean)iuw.invoke(null, url); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } if (shouldAllowNavigation == null) { try { Method gpm = webView.getClass().getMethod("getPluginManager"); PluginManager pm = (PluginManager)gpm.invoke(webView); Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class); shouldAllowNavigation = (Boolean)san.invoke(pm, url); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } return shouldAllowNavigation; } /** * Called when the view navigates. */ @Override public void onReset() { closeDialog(); } /** * Called when the system is about to start resuming a previous activity. */ @Override public void onPause(boolean multitasking) { if (shouldPauseInAppBrowser) { inAppWebView.onPause(); } } /** * Called when the activity will start interacting with the user. */ @Override public void onResume(boolean multitasking) { if (shouldPauseInAppBrowser) { inAppWebView.onResume(); } } /** * Called by AccelBroker when listener is to be shut down. * Stop listener. */ public void onDestroy() { closeDialog(); } /** * Inject an object (script or style) into the InAppBrowser WebView. * * This is a helper method for the inject{Script|Style}{Code|File} API calls, which * provides a consistent method for injecting JavaScript code into the document. * * If a wrapper string is supplied, then the source string will be JSON-encoded (adding * quotes) and wrapped using string formatting. (The wrapper string should have a single * '%s' marker) * * @param source The source object (filename or script/style text) to inject into * the document. * @param jsWrapper A JavaScript string to wrap the source string in, so that the object * is properly injected, or null if the source string is JavaScript text * which should be executed directly. */ private void injectDeferredObject(String source, String jsWrapper) { String scriptToInject; if (jsWrapper != null) { org.json.JSONArray jsonEsc = new org.json.JSONArray(); jsonEsc.put(source); String jsonRepr = jsonEsc.toString(); String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1); scriptToInject = String.format(jsWrapper, jsonSourceString); } else { scriptToInject = source; } final String finalScriptToInject = scriptToInject; this.cordova.getActivity().runOnUiThread(new Runnable() { @SuppressLint("NewApi") @Override public void run() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { // This action will have the side-effect of blurring the currently focused element inAppWebView.loadUrl("javascript:" + finalScriptToInject); } else { inAppWebView.evaluateJavascript(finalScriptToInject, null); } } }); } /** * Put the list of features into a hash map * * @param optString * @return */ private HashMap<String, Boolean> parseFeature(String optString) { if (optString.equals(NULL)) { return null; } else { HashMap<String, Boolean> map = new HashMap<String, Boolean>(); StringTokenizer features = new StringTokenizer(optString, ","); StringTokenizer option; while(features.hasMoreElements()) { option = new StringTokenizer(features.nextToken(), "="); if (option.hasMoreElements()) { String key = option.nextToken(); Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE; map.put(key, value); } } return map; } } /** * Display a new browser with the specified URL. * * @param url the url to load. * @return "" if ok, or error message. */ public String openExternal(String url) { try { Intent intent = null; intent = new Intent(Intent.ACTION_VIEW); // Omitting the MIME type for file: URLs causes "No Activity found to handle Intent". // Adding the MIME type to http: URLs causes them to not be handled by the downloader. Uri uri = Uri.parse(url); if ("file".equals(uri.getScheme())) { intent.setDataAndType(uri, webView.getResourceApi().getMimeType(uri)); } else { intent.setData(uri); } intent.putExtra(Browser.EXTRA_APPLICATION_ID, cordova.getActivity().getPackageName()); this.cordova.getActivity().startActivity(intent); return ""; } catch (android.content.ActivityNotFoundException e) { LOG.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString()); return e.toString(); } } /** * Closes the dialog */ public void closeDialog() { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { final WebView childView = inAppWebView; // The JS protects against multiple calls, so this should happen only when // closeDialog() is called by other native code. if (childView == null) { return; } childView.setWebViewClient(new WebViewClient() { // NB: wait for about:blank before dismissing public void onPageFinished(WebView view, String url) { if (dialog != null) { dialog.dismiss(); dialog = null; } } }); // NB: From SDK 19: "If you call methods on WebView from any thread // other than your app's UI thread, it can cause unexpected results." // http://developer.android.com/guide/webapps/migrating.html#Threads childView.loadUrl("about:blank"); childView.destroy(); try { JSONObject obj = new JSONObject(); obj.put("type", EXIT_EVENT); sendUpdate(obj, false); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } }); } /** * Checks to see if it is possible to go back one page in history, then does so. */ public void goBack() { if (this.inAppWebView.canGoBack()) { this.inAppWebView.goBack(); } } /** * Can the web browser go back? * @return boolean */ public boolean canGoBack() { return this.inAppWebView.canGoBack(); } /** * Has the user set the hardware back button to go back * @return boolean */ public boolean hardwareBack() { return hadwareBackButton; } /** * Checks to see if it is possible to go forward one page in history, then does so. */ private void goForward() { if (this.inAppWebView.canGoForward()) { this.inAppWebView.goForward(); } } /** * Navigate to the new page * * @param url to load */ private void navigate(String url) { InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0); if (!url.startsWith("http") && !url.startsWith("file:")) { this.inAppWebView.loadUrl("http://" + url); } else { this.inAppWebView.loadUrl(url); } this.inAppWebView.requestFocus(); } /** * Should we show the location bar? * * @return boolean */ private boolean getShowLocationBar() { return this.showLocationBar; } private InAppBrowser getInAppBrowser(){ return this; } /** * Display a new browser with the specified URL. * * @param url the url to load. * @param features jsonObject */ public String showWebPage(final String url, HashMap<String, Boolean> features) { // Determine if we should hide the location bar. showLocationBar = true; showZoomControls = true; openWindowHidden = false; mediaPlaybackRequiresUserGesture = false; if (features != null) { Boolean show = features.get(LOCATION); if (show != null) { showLocationBar = show.booleanValue(); } Boolean zoom = features.get(ZOOM); if (zoom != null) { showZoomControls = zoom.booleanValue(); } Boolean hidden = features.get(HIDDEN); if (hidden != null) { openWindowHidden = hidden.booleanValue(); } Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON); if (hardwareBack != null) { hadwareBackButton = hardwareBack.booleanValue(); } Boolean mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION); if (mediaPlayback != null) { mediaPlaybackRequiresUserGesture = mediaPlayback.booleanValue(); } Boolean cache = features.get(CLEAR_ALL_CACHE); if (cache != null) { clearAllCache = cache.booleanValue(); } else { cache = features.get(CLEAR_SESSION_CACHE); if (cache != null) { clearSessionCache = cache.booleanValue(); } } Boolean shouldPause = features.get(SHOULD_PAUSE); if (shouldPause != null) { shouldPauseInAppBrowser = shouldPause.booleanValue(); } } final CordovaWebView thatWebView = this.webView; // Create dialog in new thread Runnable runnable = new Runnable() { /** * Convert our DIP units to Pixels * * @return int */ private int dpToPixels(int dipValue) { int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, (float) dipValue, cordova.getActivity().getResources().getDisplayMetrics() ); return value; } @SuppressLint("NewApi") public void run() { // CB-6702 InAppBrowser hangs when opening more than one instance if (dialog != null) { dialog.dismiss(); }; // Let's create the main dialog dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar); dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setInAppBroswer(getInAppBrowser()); // Main container layout LinearLayout main = new LinearLayout(cordova.getActivity()); main.setOrientation(LinearLayout.VERTICAL); // Toolbar layout RelativeLayout toolbar = new RelativeLayout(cordova.getActivity()); //Please, no more black! toolbar.setBackgroundColor(android.graphics.Color.LTGRAY); toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44))); toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2)); toolbar.setHorizontalGravity(Gravity.LEFT); toolbar.setVerticalGravity(Gravity.TOP); // Action Button Container layout RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity()); actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); actionButtonContainer.setHorizontalGravity(Gravity.LEFT); actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); actionButtonContainer.setId(Integer.valueOf(1)); // Back button ImageButton back = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT); back.setLayoutParams(backLayoutParams); back.setContentDescription("Back Button"); back.setId(Integer.valueOf(2)); Resources activityRes = cordova.getActivity().getResources(); int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName()); Drawable backIcon = activityRes.getDrawable(backResId); if (Build.VERSION.SDK_INT >= 16) back.setBackground(null); else back.setBackgroundDrawable(null); back.setImageDrawable(backIcon); back.setScaleType(ImageView.ScaleType.FIT_CENTER); back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10)); if (Build.VERSION.SDK_INT >= 16) back.getAdjustViewBounds(); back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goBack(); } }); // Forward button ImageButton forward = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2); forward.setLayoutParams(forwardLayoutParams); forward.setContentDescription("Forward Button"); forward.setId(Integer.valueOf(3)); int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName()); Drawable fwdIcon = activityRes.getDrawable(fwdResId); if (Build.VERSION.SDK_INT >= 16) forward.setBackground(null); else forward.setBackgroundDrawable(null); forward.setImageDrawable(fwdIcon); forward.setScaleType(ImageView.ScaleType.FIT_CENTER); forward.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10)); if (Build.VERSION.SDK_INT >= 16) forward.getAdjustViewBounds(); forward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goForward(); } }); // Edit Text Box edittext = new EditText(cordova.getActivity()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setId(Integer.valueOf(4)); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { navigate(edittext.getText().toString()); return true; } return false; } }); // Close/Done button ImageButton close = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); close.setLayoutParams(closeLayoutParams); forward.setContentDescription("Close Button"); close.setId(Integer.valueOf(5)); int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName()); Drawable closeIcon = activityRes.getDrawable(closeResId); if (Build.VERSION.SDK_INT >= 16) close.setBackground(null); else close.setBackgroundDrawable(null); close.setImageDrawable(closeIcon); close.setScaleType(ImageView.ScaleType.FIT_CENTER); back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10)); if (Build.VERSION.SDK_INT >= 16) close.getAdjustViewBounds(); close.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeDialog(); } }); // WebView inAppWebView = new WebView(cordova.getActivity()); inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); inAppWebView.setId(Integer.valueOf(6)); inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView)); WebViewClient client = new InAppBrowserClient(thatWebView, edittext); inAppWebView.setWebViewClient(client); WebSettings settings = inAppWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(showZoomControls); settings.setPluginState(android.webkit.WebSettings.PluginState.ON); if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture); } String overrideUserAgent = preferences.getString("OverrideUserAgent", null); String appendUserAgent = preferences.getString("AppendUserAgent", null); if (overrideUserAgent != null) { settings.setUserAgentString(overrideUserAgent); } if (appendUserAgent != null) { settings.setUserAgentString(settings.getUserAgentString() + appendUserAgent); } //Toggle whether this is enabled or not! Bundle appSettings = cordova.getActivity().getIntent().getExtras(); boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true); if (enableDatabase) { String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); settings.setDatabaseEnabled(true); } settings.setDomStorageEnabled(true); if (clearAllCache) { CookieManager.getInstance().removeAllCookie(); } else if (clearSessionCache) { CookieManager.getInstance().removeSessionCookie(); } inAppWebView.loadUrl(url); inAppWebView.setId(Integer.valueOf(6)); inAppWebView.getSettings().setLoadWithOverviewMode(true); inAppWebView.getSettings().setUseWideViewPort(true); inAppWebView.requestFocus(); inAppWebView.requestFocusFromTouch(); // Add the back and forward buttons to our action button container layout actionButtonContainer.addView(back); actionButtonContainer.addView(forward); // Add the views to our toolbar toolbar.addView(actionButtonContainer); toolbar.addView(edittext); toolbar.addView(close); // Don't add the toolbar if its been disabled if (getShowLocationBar()) { // Add our toolbar to our main view/layout main.addView(toolbar); } // Add our webview to our main view/layout main.addView(inAppWebView); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); // the goal of openhidden is to load the url and not display it // Show() needs to be called to cause the URL to be loaded if(openWindowHidden) { dialog.hide(); } } }; this.cordova.getActivity().runOnUiThread(runnable); return ""; } /** * Create a new plugin success result and send it back to JavaScript * * @param obj a JSONObject contain event payload information */ private void sendUpdate(JSONObject obj, boolean keepCallback) { sendUpdate(obj, keepCallback, PluginResult.Status.OK); } /** * Create a new plugin result and send it back to JavaScript * * @param obj a JSONObject contain event payload information * @param status the status code to return to the JavaScript environment */ private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) { if (callbackContext != null) { PluginResult result = new PluginResult(status, obj); result.setKeepCallback(keepCallback); callbackContext.sendPluginResult(result); if (!keepCallback) { callbackContext = null; } } } /** * The webview client receives notifications about appView */ public class InAppBrowserClient extends WebViewClient { EditText edittext; CordovaWebView webView; /** * Constructor. * * @param webView * @param mEditText */ public InAppBrowserClient(CordovaWebView webView, EditText mEditText) { this.webView = webView; this.edittext = mEditText; } /** * Override the URL that should be loaded * * This handles a small subset of all the URIs that would be encountered. * * @param webView * @param url */ @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) { if (url.startsWith(WebView.SCHEME_TEL)) { try { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString()); } } else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:") || url.startsWith("intent:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString()); } } // If sms:5551212?body=This is the message else if (url.startsWith("sms:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); // Get address String address = null; int parmIndex = url.indexOf('?'); if (parmIndex == -1) { address = url.substring(4); } else { address = url.substring(4, parmIndex); // If body, then set sms body Uri uri = Uri.parse(url); String query = uri.getQuery(); if (query != null) { if (query.startsWith("body=")) { intent.putExtra("sms_body", query.substring(5)); } } } intent.setData(Uri.parse("sms:" + address)); intent.putExtra("address", address); intent.setType("vnd.android-dir/mms-sms"); cordova.getActivity().startActivity(intent); return true; } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString()); } } return false; } /* * onPageStarted fires the LOAD_START_EVENT * * @param view * @param url * @param favicon */ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); String newloc = ""; if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) { newloc = url; } else { // Assume that everything is HTTP at this point, because if we don't specify, // it really should be. Complain loudly about this!!! LOG.e(LOG_TAG, "Possible Uncaught/Unknown URI"); newloc = "http://" + url; } // Update the UI if we haven't already if (!newloc.equals(edittext.getText().toString())) { edittext.setText(newloc); } try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_START_EVENT); obj.put("url", newloc); sendUpdate(obj, true); } catch (JSONException ex) { LOG.e(LOG_TAG, "URI passed in has caused a JSON error."); } } public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().flush(); } else { CookieSyncManager.getInstance().sync(); } try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_STOP_EVENT); obj.put("url", url); sendUpdate(obj, true); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_ERROR_EVENT); obj.put("url", failingUrl); obj.put("code", errorCode); obj.put("message", description); sendUpdate(obj, true, PluginResult.Status.ERROR); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } } /** * On received http auth request. */ @Override public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { // Check if there is some plugin which can resolve this auth challenge PluginManager pluginManager = null; try { Method gpm = webView.getClass().getMethod("getPluginManager"); pluginManager = (PluginManager)gpm.invoke(webView); } catch (NoSuchMethodException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (InvocationTargetException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } if (pluginManager == null) { try { Field pmf = webView.getClass().getField("pluginManager"); pluginManager = (PluginManager)pmf.get(webView); } catch (NoSuchFieldException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } catch (IllegalAccessException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } } if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(webView, new CordovaHttpAuthHandler(handler), host, realm)) { return; } // By default handle 401 like we'd normally do! super.onReceivedHttpAuthRequest(view, handler, host, realm); } } }
testing logic
src/android/InAppBrowser.java
testing logic
<ide><path>rc/android/InAppBrowser.java <ide> if(args == null){ <ide> showDialogue(); <ide> } <add> else { <add> showDialogue(); <add> } <ide> // String jsWrapper = String.format("(function(){" + <ide> // "prompt(JSON.stringify([eval(%s)]))" + <ide> // "})()", args ); <ide> <ide> String url = args.getString(0); <ide> <del> if (url == null || url.equals("") || url.equals(NULL)) { <del> <del> } <add>// if (url == null || url.equals("") || url.equals(NULL)) { <add>// <add>// } <ide> <ide> <ide>
JavaScript
agpl-3.0
e2ef6b1b945bff308aa63fa201fdc99c322d50ff
0
eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql
var __kFnMagic = "\b\bFN<1337Z12323<\b\b"; function __log() { var parts = []; for (var i = 0; i < arguments.length; ++i) { parts.push(String(arguments[i])); } z1_log(parts.join(", ")); } function __encode_js(obj) { var replacer = function(key, value) { switch (typeof value) { case "string": return value; case "object": return value; case "boolean": return value; case "number": return value; case "function": return __kFnMagic + String(value); default: return undefined; } }; switch (typeof obj) { case "function": return __kFnMagic + String(obj); default: return JSON.stringify(obj, replacer); } } function __decode_js(str) { var decode_fn = function(str) { eval("__load_fn = " + str); var fn = __load_fn; delete __load_fn; return fn; } var reviver = function(key, value) { switch (typeof value) { case "string": if (value.indexOf(__kFnMagic) == 0) { return decode_fn(value.substr(__kFnMagic.length)); } else { return value; } default: return value; } }; if (str.indexOf(__kFnMagic) == 0) { return decode_fn(str.substr(__kFnMagic.length)); } else { return JSON.parse(str, reviver); } } function __call_with_iter(key, iter) { var iter_wrap = (function(iter) { return { hasNext: function() { return iter.hasNext.apply(iter, arguments); }, next: function() { return iter.next.apply(iter, arguments); }, }; })(iter); return __fn.call(this, key, iter_wrap); } var __load_closure = (function(global_scope) { return function(fn, globals_json, params_json) { var globals = __decode_js(globals_json); for (k in globals) { global_scope[k] = globals[k]; } global_scope["params"] = __decode_js(params_json); eval("__fn = " + fn); } })(this); var console = { log: function() { __log.apply(this, arguments); } }; var Z1 = (function(global) { var seq = 0; var jobs = {}; var bcastdata = {}; function mkJobID() { return "job-" + ++seq; }; function executeJob(root_job) { var dependencies = []; var dependencies_set = {}; dependencies.push(root_job); var find_dependecies = function(job) { if (job.sources) { job.sources.forEach(function(job_id) { if (dependencies_set[job_id]) { return; } var job = jobs[job_id]; if (!job) { throw "invalid job id: " + job_id; } dependencies_set[job_id] = true; dependencies.push(job); find_dependecies(job); }); } }; find_dependecies(root_job); z1_executemr(JSON.stringify(dependencies), root_job.id); } function autoBroadcast() { for (k in global) { if (typeof global[k] == "function") { Z1.broadcast(k); } } } /* public api */ var api = {}; api.log = function() { __log.apply(this, arguments); } api.broadcast = function() { for (var i = 0; i < arguments.length; ++i) { var var_name = arguments[i]; if (typeof var_name != "string") { throw "arguments to Z1.broadcast must be strings"; } if (var_name == "params") { throw "'params' is a reserved variable and cannot be broadcasted"; } if (!global.hasOwnProperty(var_name)) { throw "no such variable in the global namespace: '" + var_name + "' -- all broadcast variables must be global"; } bcastdata[var_name] = global[var_name]; } }; api.mapTable = function(opts) { autoBroadcast(); var job_id = mkJobID(); jobs[job_id] = { id: job_id, op: "map_table", table_name: opts["table"], from: opts["from"], until: opts["until"], map_fn: String(opts["map_fn"]), globals: __encode_js(bcastdata), params: __encode_js(opts["params"] || {}) }; return job_id; }; api.reduce = function(opts) { autoBroadcast(); var job_id = mkJobID(); jobs[job_id] = { id: job_id, op: "reduce", sources: opts["sources"], num_shards: opts["shards"], reduce_fn: String(opts["reduce_fn"]), globals: __encode_js(bcastdata), params: __encode_js(opts["params"] || {}) }; return job_id; }; api.downloadResults = function(sources) { executeJob({ id: mkJobID(), op: "return_results", sources: sources }); }; api.saveToTable = function(opts) { executeJob({ id: mkJobID(), op: "save_to_table", table_name: opts["table"], sources: opts["sources"] }); }; api.saveToTablePartition = function(opts) { executeJob({ id: mkJobID(), op: "save_to_table_partition", table_name: opts["table"], partition_key: opts["partition"], sources: opts["sources"] }); }; api.processStream = function(opts) { var calculate_fn = opts["calculate_fn"]; var partitions = z1_listpartitions( "" + opts["table"], "" + opts["from"], "" + opts["until"]); partitions.forEach(function(partition) { var partition_sources = calculate_fn( parseInt(partition.time_begin, 10), parseInt(partition.time_limit, 10)); if (typeof partition_sources != "object") { throw "Z1.processStream calculate_fn must return a list of jobs"; } api.saveToTablePartition({ table: opts["table"], partition: partition.partition_key, sources: partition_sources }); }); } return api; })(this);
src/zbase/mapreduce/prelude.js
var __kFnMagic = "\b\bFN<1337Z12323<\b\b"; function __log() { var parts = []; for (var i = 0; i < arguments.length; ++i) { parts.push(String(arguments[i])); } z1_log(parts.join(", ")); } function __encode_js(obj) { var replacer = function(key, value) { switch (typeof value) { case "string": return value; case "object": return value; case "boolean": return value; case "number": return value; case "function": return __kFnMagic + String(value); default: return undefined; } }; switch (typeof obj) { case "function": return __kFnMagic + String(obj); default: return JSON.stringify(obj, replacer); } } function __decode_js(str) { var decode_fn = function(str) { eval("__load_fn = " + str); var fn = __load_fn; delete __load_fn; return fn; } var reviver = function(key, value) { switch (typeof value) { case "string": if (value.indexOf(__kFnMagic) == 0) { return decode_fn(value.substr(__kFnMagic.length)); } else { return value; } default: return value; } }; if (str.indexOf(__kFnMagic) == 0) { return decode_fn(str.substr(__kFnMagic.length)); } else { return JSON.parse(str, reviver); } } function __call_with_iter(key, iter) { var iter_wrap = (function(iter) { return { hasNext: function() { return iter.hasNext.apply(iter, arguments); }, next: function() { return iter.next.apply(iter, arguments); }, }; })(iter); return __fn.call(this, key, iter_wrap); } var __load_closure = (function(global_scope) { return function(fn, globals_json, params_json) { var globals = __decode_js(globals_json); for (k in globals) { global_scope[k] = globals[k]; } global_scope["params"] = __decode_js(params_json); eval("__fn = " + fn); } })(this); var console = { log: function() { __log.apply(this, arguments); } }; var Z1 = (function(global) { var seq = 0; var jobs = {}; var bcastdata = {}; function mkJobID() { return "job-" + ++seq; }; function executeJob(root_job) { var dependencies = []; var dependencies_set = {}; dependencies.push(root_job); var find_dependecies = function(job) { if (job.sources) { job.sources.forEach(function(job_id) { if (dependencies_set[job_id]) { return; } var job = jobs[job_id]; if (!job) { throw "invalid job id: " + job_id; } dependencies_set[job_id] = true; dependencies.push(job); find_dependecies(job); }); } }; find_dependecies(root_job); z1_executemr(JSON.stringify(dependencies), root_job.id); } /* public api */ var api = {}; api.log = function() { __log.apply(this, arguments); } api.broadcast = function() { for (var i = 0; i < arguments.length; ++i) { var var_name = arguments[i]; if (typeof var_name != "string") { throw "arguments to Z1.broadcast must be strings"; } if (var_name == "params") { throw "'params' is a reserved variable and cannot be broadcasted"; } if (!global.hasOwnProperty(var_name)) { throw "no such variable in the global namespace: '" + var_name + "' -- all broadcast variables must be global"; } bcastdata[var_name] = global[var_name]; } }; api.mapTable = function(opts) { var job_id = mkJobID(); jobs[job_id] = { id: job_id, op: "map_table", table_name: opts["table"], from: opts["from"], until: opts["until"], map_fn: String(opts["map_fn"]), globals: __encode_js(bcastdata), params: __encode_js(opts["params"] || {}) }; return job_id; }; api.reduce = function(opts) { var job_id = mkJobID(); jobs[job_id] = { id: job_id, op: "reduce", sources: opts["sources"], num_shards: opts["shards"], reduce_fn: String(opts["reduce_fn"]), globals: __encode_js(bcastdata), params: __encode_js(opts["params"] || {}) }; return job_id; }; api.downloadResults = function(sources) { executeJob({ id: mkJobID(), op: "return_results", sources: sources }); }; api.saveToTable = function(opts) { executeJob({ id: mkJobID(), op: "save_to_table", table_name: opts["table"], sources: opts["sources"] }); }; api.saveToTablePartition = function(opts) { executeJob({ id: mkJobID(), op: "save_to_table_partition", table_name: opts["table"], partition_key: opts["partition"], sources: opts["sources"] }); }; api.processStream = function(opts) { var calculate_fn = opts["calculate_fn"]; var partitions = z1_listpartitions( "" + opts["table"], "" + opts["from"], "" + opts["until"]); partitions.forEach(function(partition) { var partition_sources = calculate_fn( parseInt(partition.time_begin, 10), parseInt(partition.time_limit, 10)); if (typeof partition_sources != "object") { throw "Z1.processStream calculate_fn must return a list of jobs"; } api.saveToTablePartition({ table: opts["table"], partition: partition.partition_key, sources: partition_sources }); }); } return api; })(this);
auto-broadcast global functions
src/zbase/mapreduce/prelude.js
auto-broadcast global functions
<ide><path>rc/zbase/mapreduce/prelude.js <ide> z1_executemr(JSON.stringify(dependencies), root_job.id); <ide> } <ide> <add> function autoBroadcast() { <add> for (k in global) { <add> if (typeof global[k] == "function") { <add> Z1.broadcast(k); <add> } <add> } <add> } <add> <ide> /* public api */ <ide> var api = {}; <ide> <ide> }; <ide> <ide> api.mapTable = function(opts) { <add> autoBroadcast(); <ide> var job_id = mkJobID(); <ide> <ide> jobs[job_id] = { <ide> }; <ide> <ide> api.reduce = function(opts) { <add> autoBroadcast(); <ide> var job_id = mkJobID(); <ide> <ide> jobs[job_id] = {
Java
mit
b6fa83e5b999e5cab6fec766466a619590ac2331
0
codistmonk/Aurochs
package net.sourceforge.aurochs2.core; import static net.sourceforge.aprog.tools.Tools.cast; import static net.sourceforge.aprog.tools.Tools.set; import static org.junit.Assert.*; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import net.sourceforge.aprog.tools.Tools; import net.sourceforge.aurochs2.core.LALR1Test.Grammar.Rule; import org.junit.Test; /** * @author codistmonk (creation 2014-08-24) */ public final class LALR1Test { @Test public final void test() { final Grammar grammar = new Grammar(); grammar.new Rule("()", "E"); grammar.new Rule("E", "E", '+', "E"); grammar.new Rule("E", "E", '-', "E"); grammar.new Rule("E", '-', "E"); grammar.new Rule("E", "E", "E"); grammar.new Rule("E", '(', "E", ')'); grammar.new Rule("E", '1'); { final Map<Object, Collection<Object>> firsts = grammar.getFirsts(); assertEquals(set("()", "E"), firsts.keySet()); assertEquals(set('-', '(', '1'), new HashSet<>(firsts.get("()"))); assertEquals(set('-', '(', '1'), new HashSet<>(firsts.get("E"))); } final LALR1ClosureTable closureTable = new LALR1ClosureTable(grammar); Tools.debugPrint(closureTable.getStates().size()); } /** * @author codistmonk (creation 2014-08-24) */ public static final class LALR1ClosureTable implements Serializable { private final List<State> states; public LALR1ClosureTable(final Grammar grammar) { this.states = new ArrayList<State>(); this.states.add(new State(grammar, set(new Item(grammar.getRules().get(0), 0, set(Special.END_TERMINAL))))); for (int i = 0; i < this.states.size(); ++i) { final State state = this.states.get(i); final Map<Object, Collection<Item>> nextKernels = new HashMap<>(); for (final Item item : state.getClosure()) { if (item.hasNextSymbol()) { nextKernels.compute(item.getNextSymbol(), (k, v) -> v == null ? new HashSet<>() : v).add( new Item(item.getRule(), item.getCursorIndex() + 1, item.getLookAheads())); } } for (final Map.Entry<Object, Collection<Item>> entry : nextKernels.entrySet()) { boolean addNewState = true; Tools.debugPrint(); Tools.debugPrint(entry.getValue()); for (int j = 0; j < this.states.size(); ++j) { Tools.debugPrint(entry.getValue().equals(this.states.get(j).getKernel()), this.states.get(j).getKernel()); if (entry.getValue().equals(this.states.get(j).getKernel())) { addNewState = false; if (state.getTransitions().put(entry.getKey(), j) != null) { throw new IllegalStateException(); } } } if (addNewState) { this.states.add(new State(grammar, entry.getValue())); } } } for (final State state : this.states) { Tools.debugPrint(state.getKernel()); } } public final List<State> getStates() { return this.states; } /** * {@value}. */ private static final long serialVersionUID = -632237351102999005L; /** * @author codistmonk (creation 2014-08-24) */ public final class State implements Serializable { private final Collection<Item> kernel; private final Set<Item> closure; private final Map<Object, Integer> transitions; public State(final Grammar grammar, final Collection<Item> kernel) { this.kernel = kernel; this.closure = new HashSet<>(); this.transitions = new HashMap<>(); final List<Item> todo = new ArrayList<>(kernel); while (!todo.isEmpty()) { final Item item = todo.remove(0); boolean addItemToClosure = true; for (final Item existingItem : this.closure) { if (item.equals(existingItem)) { existingItem.getLookAheads().addAll(item.getLookAheads()); addItemToClosure = false; break; } } if (addItemToClosure) { this.closure.add(item); if (item.hasNextSymbol()) { final Object nextSymbol = item.getNextSymbol(); final Set<Object> nextLookAheads = item.getNextLookAheads(); for (final Rule rule : grammar.getRules()) { if (nextSymbol.equals(rule.getNonterminal())) { todo.add(new Item(rule, 0, nextLookAheads)); } } } } } } public final Collection<Item> getKernel() { return this.kernel; } public final Collection<Item> getClosure() { return this.closure; } public final Map<Object, Integer> getTransitions() { return this.transitions; } /** * {@value}. */ private static final long serialVersionUID = 4682355118829727025L; } /** * @author codistmonk (creation 2014-08-24) */ public static enum Special { END_TERMINAL; } /** * @author codistmonk (creation 2014-08-24) */ public static final class Item implements Serializable { private final Grammar.Rule rule; private final int cursorIndex; private final Set<Object> lookAheads; public Item(final Rule rule, final int cursorIndex, final Set<Object> lookAheads) { this.rule = rule; this.cursorIndex = cursorIndex; this.lookAheads = lookAheads; } public final Grammar.Rule getRule() { return this.rule; } public final int getCursorIndex() { return this.cursorIndex; } public final Set<Object> getLookAheads() { return this.lookAheads; } public final boolean hasNextSymbol() { return this.getCursorIndex() < this.getRule().getDevelopment().length; } public final Object getNextSymbol() { return this.getRule().getDevelopment()[this.getCursorIndex()]; } public final Set<Object> getNextLookAheads() { final Grammar grammar = this.getRule().getGrammar(); final Set<Object> nonterminals = grammar.getNonterminals(); final Set<Object> collapsables = grammar.getCollapsables(); final Map<Object, Collection<Object>> firsts = grammar.getFirsts(); final Set<Object> result = new HashSet<>(); final Object[] development = this.getRule().getDevelopment(); final int n = development.length; int i; for (i = this.getCursorIndex() + 1; i < n; ++i) { final Object symbol = development[i]; final boolean symbolIsTerminal = !nonterminals.contains(symbol); if (symbolIsTerminal) { result.add(symbol); break; } result.addAll(firsts.get(symbol)); if (!collapsables.contains(symbol)) { break; } } if (i == n) { result.addAll(this.getLookAheads()); } return result; } @Override public final int hashCode() { return this.getRule().getIndex() + this.getCursorIndex(); } @Override public final boolean equals(final Object object) { final Item that = cast(this.getClass(), object); return that != null && this.getRule().getIndex() == that.getRule().getIndex() && this.getCursorIndex() == that.getCursorIndex(); } @Override public final String toString() { final StringBuilder resultBuilder = new StringBuilder(); final Object[] development = this.getRule().getDevelopment(); final int n = development.length; resultBuilder.append('[').append(this.getRule().getNonterminal()).append(" -> "); for (int i = 0; i < n; ++i) { resultBuilder.append(i == this.getCursorIndex() ? '.' : ' ').append(development[i]); } if (this.getCursorIndex() == n) { resultBuilder.append('.'); } resultBuilder.append(", ").append(Tools.join("/", this.getLookAheads().toArray())).append(']'); return resultBuilder.toString(); } /** * {@value}. */ private static final long serialVersionUID = 6541348303501689133L; } } /** * @author codistmonk (creation 2014-08-24) */ public static final class Grammar implements Serializable { private final List<Rule> rules = new ArrayList<>(); private final Set<Object> nonterminals = new HashSet<>(); private final Set<Object> collapsables = new HashSet<>(); private Map<Object, Collection<Object>> firsts; public final List<Rule> getRules() { return this.rules; } public final Set<Object> getNonterminals() { return this.nonterminals; } public final Set<Object> getCollapsables() { return this.collapsables; } public final Map<Object, Collection<Object>> getFirsts() { if (this.firsts == null) { final Set<Object> nonterminals = this.getNonterminals(); this.firsts = new HashMap<>(); for (final Object nonterminal: nonterminals) { this.firsts.put(nonterminal, new HashSet<>()); } boolean notDone; do { notDone = false; for (final Rule rule : this.getRules()) { final Object nonterminal = rule.getNonterminal(); final Object[] development = rule.getDevelopment(); final int n = development.length; final Collection<Object> nonterminalFirsts = this.firsts.get(nonterminal); int i; for (i = 0; i < n; ++i) { final Object symbol = development[i]; final boolean symbolIsTerminal = !nonterminals.contains(symbol); if (symbolIsTerminal) { notDone |= nonterminalFirsts.add(symbol); break; } notDone |= nonterminalFirsts.addAll(this.firsts.get(symbol)); if (!this.collapsables.contains(symbol)) { break; } } if (i == n) { notDone |= this.collapsables.add(nonterminal); } } } while (notDone); } return this.firsts; } final void checkEditable() { if (this.firsts != null) { throw new IllegalStateException(); } } /** * {@value}. */ private static final long serialVersionUID = 6864077963839662803L; /** * @author codistmonk (creation 2014-08-24) */ public final class Rule implements Serializable { private final int index; private final Object nonterminal; private final Object[] development; public Rule(final Object nonterminal, final Object... development) { Grammar.this.checkEditable(); final List<Rule> rules = Grammar.this.getRules(); this.index = rules.size(); this.nonterminal = nonterminal; this.development = development; rules.add(this); Grammar.this.getNonterminals().add(nonterminal); } public final Grammar getGrammar() { return Grammar.this; } public final int getIndex() { return this.index; } public final Object getNonterminal() { return this.nonterminal; } public final Object[] getDevelopment() { return this.development; } @Override public final String toString() { return this.getNonterminal() + " -> " + Arrays.toString(this.getDevelopment()); } /** * {@value}. */ private static final long serialVersionUID = 5775468391445234490L; } /** * @author codistmonk (creation 2014-08-24) */ public static abstract interface ReductionListener extends Serializable { } } }
Aurochs/test/net/sourceforge/aurochs2/core/LALR1Test.java
package net.sourceforge.aurochs2.core; import static net.sourceforge.aprog.tools.Tools.cast; import static net.sourceforge.aprog.tools.Tools.set; import static org.junit.Assert.*; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import net.sourceforge.aprog.tools.Tools; import net.sourceforge.aurochs2.core.LALR1Test.Grammar.Rule; import org.junit.Test; /** * @author codistmonk (creation 2014-08-24) */ public final class LALR1Test { @Test public final void test() { final Grammar grammar = new Grammar(); grammar.new Rule("()", "E"); grammar.new Rule("E", "E", '+', "E"); grammar.new Rule("E", "E", '-', "E"); grammar.new Rule("E", '-', "E"); grammar.new Rule("E", "E", "E"); grammar.new Rule("E", '(', "E", ')'); grammar.new Rule("E", '1'); { final Map<Object, Collection<Object>> firsts = grammar.getFirsts(); assertEquals(set("()", "E"), firsts.keySet()); assertEquals(set('-', '(', '1'), new HashSet<>(firsts.get("()"))); assertEquals(set('-', '(', '1'), new HashSet<>(firsts.get("E"))); } final LALR1ClosureTable closureTable = new LALR1ClosureTable(grammar); Tools.debugPrint(closureTable.getStates().size()); } /** * @author codistmonk (creation 2014-08-24) */ public static final class LALR1ClosureTable implements Serializable { private final List<State> states; public LALR1ClosureTable(final Grammar grammar) { this.states = new ArrayList<State>(); this.states.add(new State(grammar, set(new Item(grammar.getRules().get(0), 0, set(Special.END_TERMINAL))))); Tools.debugPrint(this.states.get(0).getKernel(), this.states.get(0).getClosure()); } public final List<State> getStates() { return this.states; } /** * {@value}. */ private static final long serialVersionUID = -632237351102999005L; /** * @author codistmonk (creation 2014-08-24) */ public final class State implements Serializable { private final Collection<Item> kernel; private final Set<Item> closure; public State(final Grammar grammar, final Collection<Item> kernel) { this.kernel = kernel; this.closure = new HashSet<>(); final List<Item> todo = new ArrayList<>(kernel); while (!todo.isEmpty()) { final Item item = todo.remove(0); boolean addItemToClosure = true; for (final Item existingItem : this.closure) { if (item.getRule().getIndex() == existingItem.getRule().getIndex() && item.getCursorIndex() == existingItem.getCursorIndex()) { existingItem.getLookAheads().addAll(item.getLookAheads()); addItemToClosure = false; break; } } if (addItemToClosure) { this.closure.add(item); if (item.hasNextSymbol()) { final Object nextSymbol = item.getNextSymbol(); final Set<Object> nextLookAheads = item.getNextLookAheads(); for (final Rule rule : grammar.getRules()) { if (nextSymbol.equals(rule.getNonterminal())) { todo.add(new Item(rule, 0, nextLookAheads)); } } } } } } public final Collection<Item> getKernel() { return this.kernel; } public final Collection<Item> getClosure() { return this.closure; } /** * {@value}. */ private static final long serialVersionUID = 4682355118829727025L; } /** * @author codistmonk (creation 2014-08-24) */ public static enum Special { END_TERMINAL; } /** * @author codistmonk (creation 2014-08-24) */ public static final class Item implements Serializable { private final Grammar.Rule rule; private final int cursorIndex; private final Set<Object> lookAheads; public Item(final Rule rule, final int cursorIndex, final Set<Object> lookAheads) { this.rule = rule; this.cursorIndex = cursorIndex; this.lookAheads = lookAheads; } public final Grammar.Rule getRule() { return this.rule; } public final int getCursorIndex() { return this.cursorIndex; } public final Set<Object> getLookAheads() { return this.lookAheads; } public final boolean hasNextSymbol() { return this.getCursorIndex() < this.getRule().getDevelopment().length; } public final Object getNextSymbol() { return this.getRule().getDevelopment()[this.getCursorIndex()]; } public final Set<Object> getNextLookAheads() { final Grammar grammar = this.getRule().getGrammar(); final Set<Object> nonterminals = grammar.getNonterminals(); final Set<Object> collapsables = grammar.getCollapsables(); final Map<Object, Collection<Object>> firsts = grammar.getFirsts(); final Set<Object> result = new HashSet<>(); final Object[] development = this.getRule().getDevelopment(); final int n = development.length; int i; for (i = this.getCursorIndex() + 1; i < n; ++i) { final Object symbol = development[i]; final boolean symbolIsTerminal = !nonterminals.contains(symbol); if (symbolIsTerminal) { result.add(symbol); break; } result.addAll(firsts.get(symbol)); if (!collapsables.contains(symbol)) { break; } } if (i == n) { result.addAll(this.getLookAheads()); } return result; } @Override public final int hashCode() { return this.getRule().getIndex() + this.getCursorIndex() + this.getLookAheads().hashCode(); } @Override public final boolean equals(final Object object) { final Item that = cast(this.getClass(), object); return that != null && this.getRule().getIndex() == that.getRule().getIndex() && this.getCursorIndex() == that.getCursorIndex() && this.getLookAheads().equals(that.getLookAheads()); } @Override public final String toString() { final StringBuilder resultBuilder = new StringBuilder(); final Object[] development = this.getRule().getDevelopment(); final int n = development.length; resultBuilder.append('[').append(this.getRule().getNonterminal()).append(" -> "); for (int i = 0; i < n; ++i) { resultBuilder.append(i == this.getCursorIndex() ? '.' : ' ').append(development[i]); } resultBuilder.append(", ").append(Tools.join("/", this.getLookAheads().toArray())).append(']'); return resultBuilder.toString(); } /** * {@value}. */ private static final long serialVersionUID = 6541348303501689133L; } } /** * @author codistmonk (creation 2014-08-24) */ public static final class Grammar implements Serializable { private final List<Rule> rules = new ArrayList<>(); private final Set<Object> nonterminals = new HashSet<>(); private final Set<Object> collapsables = new HashSet<>(); private Map<Object, Collection<Object>> firsts; public final List<Rule> getRules() { return this.rules; } public final Set<Object> getNonterminals() { return this.nonterminals; } public final Set<Object> getCollapsables() { return this.collapsables; } public final Map<Object, Collection<Object>> getFirsts() { if (this.firsts == null) { final Set<Object> nonterminals = this.getNonterminals(); this.firsts = new HashMap<>(); for (final Object nonterminal: nonterminals) { this.firsts.put(nonterminal, new HashSet<>()); } boolean notDone; do { notDone = false; for (final Rule rule : this.getRules()) { final Object nonterminal = rule.getNonterminal(); final Object[] development = rule.getDevelopment(); final int n = development.length; final Collection<Object> nonterminalFirsts = this.firsts.get(nonterminal); int i; for (i = 0; i < n; ++i) { final Object symbol = development[i]; final boolean symbolIsTerminal = !nonterminals.contains(symbol); if (symbolIsTerminal) { notDone |= nonterminalFirsts.add(symbol); break; } notDone |= nonterminalFirsts.addAll(this.firsts.get(symbol)); if (!this.collapsables.contains(symbol)) { break; } } if (i == n) { notDone |= this.collapsables.add(nonterminal); } } } while (notDone); } return this.firsts; } final void checkEditable() { if (this.firsts != null) { throw new IllegalStateException(); } } /** * {@value}. */ private static final long serialVersionUID = 6864077963839662803L; /** * @author codistmonk (creation 2014-08-24) */ public final class Rule implements Serializable { private final int index; private final Object nonterminal; private final Object[] development; public Rule(final Object nonterminal, final Object... development) { Grammar.this.checkEditable(); final List<Rule> rules = Grammar.this.getRules(); this.index = rules.size(); this.nonterminal = nonterminal; this.development = development; rules.add(this); Grammar.this.getNonterminals().add(nonterminal); } public final Grammar getGrammar() { return Grammar.this; } public final int getIndex() { return this.index; } public final Object getNonterminal() { return this.nonterminal; } public final Object[] getDevelopment() { return this.development; } @Override public final String toString() { return this.getNonterminal() + " -> " + Arrays.toString(this.getDevelopment()); } /** * {@value}. */ private static final long serialVersionUID = 5775468391445234490L; } /** * @author codistmonk (creation 2014-08-24) */ public static abstract interface ReductionListener extends Serializable { } } }
[Aurochs][aurochs2] Updated LALR1Test.
Aurochs/test/net/sourceforge/aurochs2/core/LALR1Test.java
[Aurochs][aurochs2] Updated LALR1Test.
<ide><path>urochs/test/net/sourceforge/aurochs2/core/LALR1Test.java <ide> <ide> this.states.add(new State(grammar, set(new Item(grammar.getRules().get(0), 0, set(Special.END_TERMINAL))))); <ide> <del> Tools.debugPrint(this.states.get(0).getKernel(), this.states.get(0).getClosure()); <add> for (int i = 0; i < this.states.size(); ++i) { <add> final State state = this.states.get(i); <add> final Map<Object, Collection<Item>> nextKernels = new HashMap<>(); <add> <add> for (final Item item : state.getClosure()) { <add> if (item.hasNextSymbol()) { <add> nextKernels.compute(item.getNextSymbol(), (k, v) -> v == null ? new HashSet<>() : v).add( <add> new Item(item.getRule(), item.getCursorIndex() + 1, item.getLookAheads())); <add> } <add> } <add> <add> for (final Map.Entry<Object, Collection<Item>> entry : nextKernels.entrySet()) { <add> boolean addNewState = true; <add> <add> Tools.debugPrint(); <add> Tools.debugPrint(entry.getValue()); <add> <add> for (int j = 0; j < this.states.size(); ++j) { <add> Tools.debugPrint(entry.getValue().equals(this.states.get(j).getKernel()), this.states.get(j).getKernel()); <add> if (entry.getValue().equals(this.states.get(j).getKernel())) { <add> addNewState = false; <add> <add> if (state.getTransitions().put(entry.getKey(), j) != null) { <add> throw new IllegalStateException(); <add> } <add> } <add> } <add> <add> if (addNewState) { <add> this.states.add(new State(grammar, entry.getValue())); <add> } <add> } <add> } <add> <add> for (final State state : this.states) { <add> Tools.debugPrint(state.getKernel()); <add> } <ide> } <ide> <ide> public final List<State> getStates() { <ide> private final Collection<Item> kernel; <ide> <ide> private final Set<Item> closure; <add> <add> private final Map<Object, Integer> transitions; <ide> <ide> public State(final Grammar grammar, final Collection<Item> kernel) { <ide> this.kernel = kernel; <ide> this.closure = new HashSet<>(); <add> this.transitions = new HashMap<>(); <ide> <ide> final List<Item> todo = new ArrayList<>(kernel); <ide> <ide> boolean addItemToClosure = true; <ide> <ide> for (final Item existingItem : this.closure) { <del> if (item.getRule().getIndex() == existingItem.getRule().getIndex() <del> && item.getCursorIndex() == existingItem.getCursorIndex()) { <add> if (item.equals(existingItem)) { <ide> existingItem.getLookAheads().addAll(item.getLookAheads()); <ide> addItemToClosure = false; <ide> break; <ide> return this.closure; <ide> } <ide> <add> public final Map<Object, Integer> getTransitions() { <add> return this.transitions; <add> } <add> <ide> /** <ide> * {@value}. <ide> */ <ide> <ide> @Override <ide> public final int hashCode() { <del> return this.getRule().getIndex() + this.getCursorIndex() + this.getLookAheads().hashCode(); <add> return this.getRule().getIndex() + this.getCursorIndex(); <ide> } <ide> <ide> @Override <ide> <ide> return that != null <ide> && this.getRule().getIndex() == that.getRule().getIndex() <del> && this.getCursorIndex() == that.getCursorIndex() && <del> this.getLookAheads().equals(that.getLookAheads()); <add> && this.getCursorIndex() == that.getCursorIndex(); <ide> } <ide> <ide> @Override <ide> <ide> for (int i = 0; i < n; ++i) { <ide> resultBuilder.append(i == this.getCursorIndex() ? '.' : ' ').append(development[i]); <add> } <add> <add> if (this.getCursorIndex() == n) { <add> resultBuilder.append('.'); <ide> } <ide> <ide> resultBuilder.append(", ").append(Tools.join("/", this.getLookAheads().toArray())).append(']');
Java
apache-2.0
70ae1995142c124438559d2d466b61198e23cdca
0
yukezhu/LifeGameSim,yukezhu/LifeGameSim,yukezhu/LifeGameSim,yukezhu/LifeGameSim
package ca.sfu.server; import java.io.IOException; import java.util.ArrayList; import ca.sfu.cmpt431.facility.Board; import ca.sfu.cmpt431.facility.BoardOperation; import ca.sfu.cmpt431.facility.Comrade; import ca.sfu.cmpt431.facility.Outfits; import ca.sfu.cmpt431.message.Message; import ca.sfu.cmpt431.message.MessageCodeDictionary; import ca.sfu.cmpt431.message.join.JoinOutfitsMsg; import ca.sfu.cmpt431.message.join.JoinRequestMsg; import ca.sfu.cmpt431.message.join.JoinSplitMsg; import ca.sfu.cmpt431.message.leave.LeaveReceiverMsg; import ca.sfu.cmpt431.message.merge.MergeLastMsg; import ca.sfu.cmpt431.message.regular.RegularBoardReturnMsg; import ca.sfu.cmpt431.message.regular.RegularNextClockMsg; import ca.sfu.network.MessageReceiver; import ca.sfu.network.MessageSender; import ca.sfu.network.SynchronizedMsgQueue.MessageWithIp; public class Server{ protected static final int LISTEN_PORT = 6560; private MessageReceiver Receiver; private MessageSender Sender1; private MessageSender Sender2; private String client1_ip; private String client2_ip; private ArrayList<MessageSender> newClientSender = new ArrayList<MessageSender>(); private ArrayList<Comrade> regedClientSender = new ArrayList<Comrade>(); private ArrayList<Integer> toLeave = new ArrayList<Integer>(); private int waiting4confirm = 0; private int nextClock = 0; private int status; private int phase; private static final int COMPUTE = 0; private static final int ADD = 1; private static final int LEAVE = 2; /* UI widgets */ MainFrame frame = null; InformationPanel infoPanel = null; public Server() throws IOException { Receiver = new MessageReceiver(LISTEN_PORT); status = 0; } protected void startServer() throws IOException, ClassNotFoundException, InterruptedException { // UI Board b = BoardOperation.LoadFile("Patterns/HerschelLoop.lg"); System.out.println("UI"); frame = new MainFrame(b, 800, 800); infoPanel = new InformationPanel(); MessageWithIp m; int result = -1; while(true) { if(!Receiver.isEmpty()) { m = Receiver.getNextMessageWithIp(); switch(status) { //waiting for first client case 0: handleNewAddingLeaving(m,1); handlePending(); //send it the outfit regedClientSender.get(0).sender.sendMsg(new JoinOutfitsMsg(-1, -1, new Outfits(0,nextClock,0,0,b))); waiting4confirm++; status = 2; break; //wait for the confirm //start a cycle case 2: if(handleNewAddingLeaving(m,2)) break; handleConfirm(m,3); //expect only one message responding for JoinOutfitsMsg if(!newClientSender.isEmpty()){ handlePending(); status = 2; break; } if(waiting4confirm == 0){ //send you a start System.out.println("sending start"); infoPanel.setCycleNum(frame.automataPanel.getCycle()); for (Comrade var : regedClientSender) { var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } status = 3; phase = COMPUTE; } break; //waiting for the client to send the result back //handle new adding or //restart next cycle case 3: if(handleNewAddingLeaving(m,3)) break; if(phase == COMPUTE){ handleNewBoardInfo(m,b,3); if(waiting4confirm!=0){ break; } // Thread.sleep(50); frame.repaint(); infoPanel.setCellNum(frame.automataPanel.getCell()); infoPanel.setLifeNum(frame.automataPanel.getAlive()); infoPanel.setTargetNum("localhost"); phase = LEAVE; // BoardOperation.Print(b); System.out.println("repaint"); } if(phase == LEAVE){ //deal with the confirm //manage the heap if(((Message)m.extracMessage()).getMessageCode()==MessageCodeDictionary.REGULAR_CONFIRM){ // System.out.println("result:"+result); if(result == 1){ int s = regedClientSender.size(); // System.out.println(regedClientSender.get(s-2).id); regedClientSender.get(s-1).sender.sendMsg(new LeaveReceiverMsg(MessageCodeDictionary.ID_SERVER, 0, "")); regedClientSender.get(s-1).sender.close(); regedClientSender.remove(s-1); Comrade c = regedClientSender.get(s-2); regedClientSender.remove(s-2); regedClientSender.add(0, c); } else if(result == 2){ int s = regedClientSender.size(); // System.out.println(regedClientSender.get(s-2).id); regedClientSender.get(s-2).sender.sendMsg(new LeaveReceiverMsg(MessageCodeDictionary.ID_SERVER, 0, "")); Comrade c = regedClientSender.get(s-1); regedClientSender.remove(s-1); regedClientSender.get(s-2).sender.close(); regedClientSender.remove(s-2); regedClientSender.add(0, c); } else if(result == 3){ int cid = toLeave.get(0); int index = findClient(cid); int s = regedClientSender.size(); regedClientSender.get(index).sender.sendMsg(new LeaveReceiverMsg(MessageCodeDictionary.ID_SERVER, 0, "")); regedClientSender.get(index).sender.close(); regedClientSender.set(index, regedClientSender.get(s-1)); regedClientSender.remove(s-1); Comrade c = regedClientSender.get(s-2); regedClientSender.remove(s-2); regedClientSender.add(0, c); } else{ //error System.out.println("error."); } toLeave.remove(0); } while((result=handleLeaving())!=-1){ //0, continue handling if(result == 0){ toLeave.remove(0); continue; } //4, no client now, go to status 0 pls else if(result == 4){ toLeave.remove(0); System.out.println("go to status 0"); status = 0; break; } else{ //wait for a confirm status = 3; break; } } if(toLeave.isEmpty() && status != 0) phase = ADD; else break; } //handle adding if(handlePending()){ status = 2; break; } //start if(waiting4confirm==0){ for (Comrade var : regedClientSender) { var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } System.out.println("sending start"); infoPanel.setCycleNum(frame.automataPanel.getCycle()); phase = COMPUTE; } break; default: break; } } } } //store all the adding request into an array protected boolean handleNewAddingLeaving(MessageWithIp m, int nextStatus) throws IOException{ //check if m is a new adding request message Message msg = (Message) m.extracMessage(); if(msg.getMessageCode()==MessageCodeDictionary.JOIN_REQUEST){ JoinRequestMsg join = (JoinRequestMsg)m.extracMessage(); newClientSender.add(new MessageSender(m.getIp(), join.clientPort)); System.out.println("adding a new client to pending list"); //if it is a new adding request, we need to go to nextStatus //most time it should be the same status status = nextStatus; return true; } else if(msg.getMessageCode()==MessageCodeDictionary.REGULAR_BOARD_RETURN){ RegularBoardReturnMsg r = (RegularBoardReturnMsg)msg; if(r.isLeaving){ toLeave.add(msg.getClientId()); System.out.println("client " + toLeave.get(toLeave.size()-1) + " want to leave, pending now"); return false; } } return false; } protected int handleLeaving() throws IOException{ if(toLeave.isEmpty()) return -1; int cid = toLeave.get(0); if(newClientSender.size()!=0){ //ask a new client to replace it immediately regedClientSender.get(0).sender.sendMsg(new LeaveReceiverMsg(MessageCodeDictionary.ID_SERVER, 0, "")); regedClientSender.get(findClient(cid)).sender.close(); regedClientSender.set(findClient(cid), new Comrade(regedClientSender.size(), newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, newClientSender.get(0))); newClientSender.remove(0); System.out.println("new adding, replace"); //TODO //no confirm return 0; } else if(regedClientSender.size()==1){ //there is only one client and no adding //ask him to leave directly regedClientSender.get(0).sender.sendMsg(new LeaveReceiverMsg(MessageCodeDictionary.ID_SERVER, 0, "")); regedClientSender.get(findClient(cid)).sender.close(); regedClientSender.remove(findClient(cid)); System.out.println("only one client, leave directly"); //no confirm, everything done, but you need to wait for a client to start return 4; } else if(isLastPair(cid)!=-1){ //it is the last node, or the pair of last node //ask the last pair merge int s = regedClientSender.size(); int pair_index = (s%2==0)?((s-4)>=0?(s-4):-1):0; System.out.println("pair index:"+pair_index); if(pair_index!=-1 && isLastPair(regedClientSender.get(pair_index).id)!=-1) pair_index = -1; //you pair can not be your neighbour, occurs when there is 2 clients System.out.println("pair index:"+pair_index); int pair_cid = -1; String pair_ip = ""; int pair_port = -1; if(pair_index!=-1){ pair_cid = regedClientSender.get(pair_index).id; pair_ip = regedClientSender.get(pair_index).ip; pair_port = regedClientSender.get(pair_index).port; } System.out.println("last pair handle pending:"+pair_cid+","+cid); regedClientSender.get(regedClientSender.size()-1-isLastPair(cid)).sender.sendMsg(new MergeLastMsg(pair_cid, pair_ip, pair_port)); //wait for a confirm, still need a LeaveReceiverMsg return isLastPair(cid)+1; //1 if last or 2 if second last } else{ //ask the last node merge first,give it a new pair id //ask the last node to replace int s = regedClientSender.size(); int pair_index = (s%2==0)?((s-4)>=0?(s-4):-1):0; int pair_cid = -1; String pair_ip = ""; int pair_port = -1; if(pair_index!=-1){ pair_cid = regedClientSender.get(pair_index).id; pair_ip = regedClientSender.get(pair_index).ip; pair_port = regedClientSender.get(pair_index).port; } System.out.println("normal merge handle pending(p/u):"+pair_cid+","+cid); regedClientSender.get(regedClientSender.size()-1).sender.sendMsg(new MergeLastMsg(pair_cid, pair_ip, pair_port)); //wait for a confirm, still need a LeaveReceiverMsg return 3; } } private int findClient(int cid){ for(int i=0; i<regedClientSender.size(); i++){ if(regedClientSender.get(i).id == cid){ return i; } } return -1; } private int isLastPair(int cid){ int s = regedClientSender.size(); if(regedClientSender.get(s-1).id == cid) return 0; else if(regedClientSender.get(s-2).id == cid) return 1; else return -1; } //deal with the pending adding request //manage the heap protected boolean handlePending() throws IOException{ //you can add at most N new clients in a cycle, N is the number of all clients existing before if(!newClientSender.isEmpty()){ int cid = regedClientSender.size(); //manage the heap if(cid!=0){ //not the first client Comrade c = regedClientSender.get(0); //get it down one level //c is the pair int mode; if((((int)(Math.log(2*cid+1)/Math.log(2)))%2)!=0) mode = MessageCodeDictionary.SPLIT_MODE_HORIZONTAL; else mode = MessageCodeDictionary.SPLIT_MODE_VERTICAL; // System.out.println(cid); // System.out.println((Math.log(2*cid+1)/Math.log(2))%2); // System.out.println("mode"+mode); System.out.println("Sending a split command to "+ c.id+", new client id: "+cid+", split mode: "+(mode==0?"vertical":"horizontal")); // System.out.println("send JoinSplitMsg"); // System.out.println(newClientSender.get(0).hostIp); c.sender.sendMsg(new JoinSplitMsg(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, mode)); regedClientSender.remove(0); regedClientSender.add(c); regedClientSender.add(new Comrade(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, newClientSender.get(0))); waiting4confirm++; } else{ regedClientSender.add(new Comrade(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, newClientSender.get(0))); //regedClientSender.get(cid).sender.sendMsg(new RegularConfirmMsg(-1)); } //remove the pending one newClientSender.remove(0); System.out.println("register a new client"); infoPanel.setClientNum(regedClientSender.size()); return true; } return false; } protected void handleNewBoardInfo(MessageWithIp m, Board b, int nextStatus){ waiting4confirm--; // System.out.println("getting a result"); if(waiting4confirm==0) status = nextStatus; RegularBoardReturnMsg r = (RegularBoardReturnMsg)m.extracMessage(); BoardOperation.Merge(b, r.board, r.top, r.left); // b = (Board)m.extracMessage(); } //getting a new confirm message, if there is no waiting confirm, go to nextStatus protected void handleConfirm(MessageWithIp m, int nextStatus){ waiting4confirm--; // System.out.println("getting a confirm"); if(waiting4confirm==0) status = nextStatus; } }
GameOfLifeServer/src/ca/sfu/server/Server.java
package ca.sfu.server; import java.io.IOException; import java.util.ArrayList; import ca.sfu.cmpt431.facility.Board; import ca.sfu.cmpt431.facility.BoardOperation; import ca.sfu.cmpt431.facility.Comrade; import ca.sfu.cmpt431.facility.Outfits; import ca.sfu.cmpt431.message.Message; import ca.sfu.cmpt431.message.MessageCodeDictionary; import ca.sfu.cmpt431.message.join.JoinOutfitsMsg; import ca.sfu.cmpt431.message.join.JoinRequestMsg; import ca.sfu.cmpt431.message.join.JoinSplitMsg; import ca.sfu.cmpt431.message.leave.LeaveReceiverMsg; import ca.sfu.cmpt431.message.merge.MergeLastMsg; import ca.sfu.cmpt431.message.regular.RegularBoardReturnMsg; import ca.sfu.cmpt431.message.regular.RegularNextClockMsg; import ca.sfu.network.MessageReceiver; import ca.sfu.network.MessageSender; import ca.sfu.network.SynchronizedMsgQueue.MessageWithIp; public class Server{ protected static final int LISTEN_PORT = 6560; private MessageReceiver Receiver; private MessageSender Sender1; private MessageSender Sender2; private String client1_ip; private String client2_ip; private ArrayList<MessageSender> newClientSender = new ArrayList<MessageSender>(); private ArrayList<Comrade> regedClientSender = new ArrayList<Comrade>(); private ArrayList<Integer> toLeave = new ArrayList<Integer>(); private int waiting4confirm = 0; private int nextClock = 0; private int status; private int phase; private static final int COMPUTE = 0; private static final int ADD = 1; private static final int LEAVE = 2; /* UI widgets */ MainFrame frame = null; InformationPanel infoPanel = null; public Server() throws IOException { Receiver = new MessageReceiver(LISTEN_PORT); status = 0; } protected void startServer() throws IOException, ClassNotFoundException, InterruptedException { // UI Board b = BoardOperation.LoadFile("Patterns/HerschelLoop.lg"); System.out.println("UI"); frame = new MainFrame(b, 800, 800); infoPanel = new InformationPanel(); MessageWithIp m; int result = -1; while(true) { if(!Receiver.isEmpty()) { m = Receiver.getNextMessageWithIp(); switch(status) { //waiting for first client case 0: handleNewAddingLeaving(m,1); handlePending(); //send it the outfit regedClientSender.get(0).sender.sendMsg(new JoinOutfitsMsg(-1, -1, new Outfits(0,nextClock,0,0,b))); waiting4confirm++; status = 2; break; //wait for the confirm //start a cycle case 2: if(handleNewAddingLeaving(m,2)) break; handleConfirm(m,3); //expect only one message responding for JoinOutfitsMsg if(!newClientSender.isEmpty()){ handlePending(); status = 2; break; } if(waiting4confirm == 0){ //send you a start System.out.println("sending start"); infoPanel.setCycleNum(frame.automataPanel.getCycle()); for (Comrade var : regedClientSender) { var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } status = 3; phase = COMPUTE; } break; //waiting for the client to send the result back //handle new adding or //restart next cycle case 3: if(handleNewAddingLeaving(m,3)) break; if(phase == COMPUTE){ handleNewBoardInfo(m,b,3); if(waiting4confirm!=0){ break; } // Thread.sleep(50); frame.repaint(); infoPanel.setCellNum(frame.automataPanel.getCell()); infoPanel.setLifeNum(frame.automataPanel.getAlive()); infoPanel.setTargetNum("localhost"); phase = LEAVE; // BoardOperation.Print(b); System.out.println("repaint"); } if(phase == LEAVE){ //deal with the confirm //manage the heap if(((Message)m.extracMessage()).getMessageCode()==MessageCodeDictionary.REGULAR_CONFIRM){ // System.out.println("result:"+result); if(result == 1){ int s = regedClientSender.size(); // System.out.println(regedClientSender.get(s-2).id); regedClientSender.get(s-1).sender.sendMsg(new LeaveReceiverMsg(MessageCodeDictionary.ID_SERVER, 0, "")); regedClientSender.get(s-1).sender.close(); regedClientSender.remove(s-1); Comrade c = regedClientSender.get(s-2); regedClientSender.remove(s-2); regedClientSender.add(0, c); } else if(result == 2){ int s = regedClientSender.size(); // System.out.println(regedClientSender.get(s-2).id); regedClientSender.get(s-2).sender.sendMsg(new LeaveReceiverMsg(MessageCodeDictionary.ID_SERVER, 0, "")); Comrade c = regedClientSender.get(s-1); regedClientSender.remove(s-1); regedClientSender.get(s-2).sender.close(); regedClientSender.remove(s-2); regedClientSender.add(0, c); } else if(result == 3){ int cid = toLeave.get(0); int index = findClient(cid); int s = regedClientSender.size(); regedClientSender.get(index).sender.sendMsg(new LeaveReceiverMsg(MessageCodeDictionary.ID_SERVER, 0, "")); regedClientSender.get(index).sender.close(); regedClientSender.set(index, regedClientSender.get(s-1)); regedClientSender.remove(s-1); Comrade c = regedClientSender.get(s-2); regedClientSender.remove(s-2); regedClientSender.add(0, c); } else{ //error System.out.println("error."); } toLeave.remove(0); } while((result=handleLeaving())!=-1){ //0, continue handling if(result == 0){ toLeave.remove(0); continue; } //4, no client now, go to status 0 pls else if(result == 4){ toLeave.remove(0); System.out.println("go to status 0"); status = 0; break; } else{ //wait for a confirm status = 3; break; } } if(toLeave.isEmpty() && status != 0) phase = ADD; else break; } //handle adding if(handlePending()){ status = 2; break; } //start if(waiting4confirm==0){ for (Comrade var : regedClientSender) { var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } System.out.println("sending start"); infoPanel.setCycleNum(frame.automataPanel.getCycle()); phase = COMPUTE; } break; default: break; } } } } //store all the adding request into an array protected boolean handleNewAddingLeaving(MessageWithIp m, int nextStatus) throws IOException{ //check if m is a new adding request message Message msg = (Message) m.extracMessage(); if(msg.getMessageCode()==MessageCodeDictionary.JOIN_REQUEST){ JoinRequestMsg join = (JoinRequestMsg)m.extracMessage(); newClientSender.add(new MessageSender(m.getIp(), join.clientPort)); System.out.println("adding a new client to pending list"); //if it is a new adding request, we need to go to nextStatus //most time it should be the same status status = nextStatus; return true; } else if(msg.getMessageCode()==MessageCodeDictionary.REGULAR_BOARD_RETURN){ RegularBoardReturnMsg r = (RegularBoardReturnMsg)msg; if(r.isLeaving){ toLeave.add(msg.getClientId()); System.out.println("a client want to leave, pending now"); return false; } } return false; } protected int handleLeaving() throws IOException{ if(toLeave.isEmpty()) return -1; int cid = toLeave.get(0); if(newClientSender.size()!=0){ //ask a new client to replace it immediately regedClientSender.get(0).sender.sendMsg(new LeaveReceiverMsg(MessageCodeDictionary.ID_SERVER, 0, "")); regedClientSender.get(findClient(cid)).sender.close(); regedClientSender.set(findClient(cid), new Comrade(regedClientSender.size(), newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, newClientSender.get(0))); newClientSender.remove(0); System.out.println("new adding, replace"); //TODO //no confirm return 0; } else if(regedClientSender.size()==1){ //there is only one client and no adding //ask him to leave directly regedClientSender.get(0).sender.sendMsg(new LeaveReceiverMsg(MessageCodeDictionary.ID_SERVER, 0, "")); regedClientSender.get(findClient(cid)).sender.close(); regedClientSender.remove(findClient(cid)); System.out.println("only one client, leave directly"); //no confirm, everything done, but you need to wait for a client to start return 4; } else if(isLastPair(cid)!=-1){ //it is the last node, or the pair of last node //ask the last pair merge int s = regedClientSender.size(); int pair_index = (s%2==0)?((s-4)>=0?(s-4):-1):0; if(isLastPair(pair_index)!=-1) pair_index = -1; //you pair can not be your neighbour, occurs when there is 2 clients int pair_cid = -1; String pair_ip = ""; int pair_port = -1; if(pair_index!=-1){ pair_cid = regedClientSender.get(pair_index).id; pair_ip = regedClientSender.get(pair_index).ip; pair_port = regedClientSender.get(pair_index).port; } System.out.println("last pair handle pending:"+pair_cid); regedClientSender.get(regedClientSender.size()-1-isLastPair(cid)).sender.sendMsg(new MergeLastMsg(pair_cid, pair_ip, pair_port)); //wait for a confirm, still need a LeaveReceiverMsg return isLastPair(cid)+1; //1 if last or 2 if second last } else{ //ask the last node merge first,give it a new pair id //ask the last node to replace int s = regedClientSender.size(); int pair_index = (s%2==0)?((s-4)>=0?(s-4):-1):0; if(isLastPair(pair_index)!=-1) pair_index = -1; //you pair can not be your brother, occurs when there is 2 clients int pair_cid = -1; String pair_ip = ""; int pair_port = -1; if(pair_index!=-1){ pair_cid = regedClientSender.get(pair_index).id; pair_ip = regedClientSender.get(pair_index).ip; pair_port = regedClientSender.get(pair_index).port; } System.out.println("nomal merge handle pending:"+pair_cid); regedClientSender.get(regedClientSender.size()-1).sender.sendMsg(new MergeLastMsg(pair_cid, pair_ip, pair_port)); //wait for a confirm, still need a LeaveReceiverMsg return 3; } } private int findClient(int cid){ for(int i=0; i<regedClientSender.size(); i++){ if(regedClientSender.get(i).id == cid){ return i; } } return -1; } private int isLastPair(int cid){ int s = regedClientSender.size(); if(regedClientSender.get(s-1).id == cid) return 0; else if(regedClientSender.get(s-2).id == cid) return 1; else return -1; } //deal with the pending adding request //manage the heap protected boolean handlePending() throws IOException{ //you can add at most N new clients in a cycle, N is the number of all clients existing before if(!newClientSender.isEmpty()){ int cid = regedClientSender.size(); //manage the heap if(cid!=0){ //not the first client Comrade c = regedClientSender.get(0); //get it down one level //c is the pair int mode; if((((int)(Math.log(2*cid+1)/Math.log(2)))%2)!=0) mode = MessageCodeDictionary.SPLIT_MODE_HORIZONTAL; else mode = MessageCodeDictionary.SPLIT_MODE_VERTICAL; // System.out.println(cid); // System.out.println((Math.log(2*cid+1)/Math.log(2))%2); // System.out.println("mode"+mode); System.out.println("Sending a split command to "+ c.id+", new client id: "+cid+", split mode: "+(mode==0?"vertical":"horizontal")); // System.out.println("send JoinSplitMsg"); // System.out.println(newClientSender.get(0).hostIp); c.sender.sendMsg(new JoinSplitMsg(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, mode)); regedClientSender.remove(0); regedClientSender.add(c); regedClientSender.add(new Comrade(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, newClientSender.get(0))); waiting4confirm++; } else{ regedClientSender.add(new Comrade(cid, newClientSender.get(0).hostListenningPort, newClientSender.get(0).hostIp, newClientSender.get(0))); //regedClientSender.get(cid).sender.sendMsg(new RegularConfirmMsg(-1)); } //remove the pending one newClientSender.remove(0); System.out.println("register a new client"); infoPanel.setClientNum(regedClientSender.size()); return true; } return false; } protected void handleNewBoardInfo(MessageWithIp m, Board b, int nextStatus){ waiting4confirm--; // System.out.println("getting a result"); if(waiting4confirm==0) status = nextStatus; RegularBoardReturnMsg r = (RegularBoardReturnMsg)m.extracMessage(); BoardOperation.Merge(b, r.board, r.top, r.left); // b = (Board)m.extracMessage(); } //getting a new confirm message, if there is no waiting confirm, go to nextStatus protected void handleConfirm(MessageWithIp m, int nextStatus){ waiting4confirm--; // System.out.println("getting a confirm"); if(waiting4confirm==0) status = nextStatus; } }
server9:29
GameOfLifeServer/src/ca/sfu/server/Server.java
server9:29
<ide><path>ameOfLifeServer/src/ca/sfu/server/Server.java <ide> RegularBoardReturnMsg r = (RegularBoardReturnMsg)msg; <ide> if(r.isLeaving){ <ide> toLeave.add(msg.getClientId()); <del> System.out.println("a client want to leave, pending now"); <add> System.out.println("client " + toLeave.get(toLeave.size()-1) + " want to leave, pending now"); <ide> return false; <ide> } <ide> } <ide> //ask the last pair merge <ide> int s = regedClientSender.size(); <ide> int pair_index = (s%2==0)?((s-4)>=0?(s-4):-1):0; <del> <del> if(isLastPair(pair_index)!=-1) <add> System.out.println("pair index:"+pair_index); <add> <add> if(pair_index!=-1 && isLastPair(regedClientSender.get(pair_index).id)!=-1) <ide> pair_index = -1; //you pair can not be your neighbour, occurs when there is 2 clients <add> <add> System.out.println("pair index:"+pair_index); <ide> <ide> int pair_cid = -1; <ide> String pair_ip = ""; <ide> pair_port = regedClientSender.get(pair_index).port; <ide> } <ide> <del> System.out.println("last pair handle pending:"+pair_cid); <add> System.out.println("last pair handle pending:"+pair_cid+","+cid); <ide> regedClientSender.get(regedClientSender.size()-1-isLastPair(cid)).sender.sendMsg(new MergeLastMsg(pair_cid, pair_ip, pair_port)); <ide> //wait for a confirm, still need a LeaveReceiverMsg <ide> return isLastPair(cid)+1; //1 if last or 2 if second last <ide> int s = regedClientSender.size(); <ide> <ide> int pair_index = (s%2==0)?((s-4)>=0?(s-4):-1):0; <del> <del> if(isLastPair(pair_index)!=-1) <del> pair_index = -1; //you pair can not be your brother, occurs when there is 2 clients <ide> <ide> int pair_cid = -1; <ide> String pair_ip = ""; <ide> pair_port = regedClientSender.get(pair_index).port; <ide> } <ide> <del> System.out.println("nomal merge handle pending:"+pair_cid); <add> System.out.println("normal merge handle pending(p/u):"+pair_cid+","+cid); <ide> regedClientSender.get(regedClientSender.size()-1).sender.sendMsg(new MergeLastMsg(pair_cid, pair_ip, pair_port)); <ide> //wait for a confirm, still need a LeaveReceiverMsg <ide> return 3;
Java
mit
fa452f5a523ab66d4fad24029928ed2b2645171d
0
kmdouglass/Micro-Manager,kmdouglass/Micro-Manager
/////////////////////////////////////////////////////////////////////////////// //FILE: VirtualAcquisitionDisplay.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio //----------------------------------------------------------------------------- // // AUTHOR: Henry Pinkard, [email protected], & Arthur Edelstein, 2010 // // COPYRIGHT: University of California, San Francisco, 2012 // // LICENSE: This file is distributed under the BSD license. // License text is included with the source distribution. // // This file is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // package org.micromanager.acquisition; import java.util.logging.Level; import java.util.logging.Logger; import org.micromanager.api.DisplayControls; import java.lang.reflect.InvocationTargetException; import org.micromanager.api.ImageCacheListener; import ij.ImageStack; import ij.process.LUT; import ij.CompositeImage; import ij.ImagePlus; import ij.WindowManager; import ij.gui.ImageCanvas; import ij.gui.ImageWindow; import ij.gui.ScrollbarWithLabel; import ij.gui.StackWindow; import ij.gui.Toolbar; import ij.io.FileInfo; import ij.measure.Calibration; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.*; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.prefs.Preferences; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.Timer; import mmcorej.TaggedImage; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.MMStudioMainFrame; import org.micromanager.api.AcquisitionEngine; import org.micromanager.api.ImageCache; import org.micromanager.utils.AcqOrderMode; import org.micromanager.utils.FileDialogs; import org.micromanager.utils.JavaUtils; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.ReportingUtils; public final class VirtualAcquisitionDisplay implements ImageCacheListener { public static VirtualAcquisitionDisplay getDisplay(ImagePlus imgp) { ImageStack stack = imgp.getStack(); if (stack instanceof AcquisitionVirtualStack) { return ((AcquisitionVirtualStack) stack).getVirtualAcquisitionDisplay(); } else { return null; } } final static Color[] rgb = {Color.red, Color.green, Color.blue}; final static String[] rgbNames = {"Red", "Blue", "Green"}; final ImageCache imageCache_; final Preferences prefs_ = Preferences.userNodeForPackage(this.getClass()); private static final String SIMPLE_WIN_X = "simple_x"; private static final String SIMPLE_WIN_Y = "simple_y"; private static final String PREF_WIN_LENGTH = "preferred_window_max_length"; private AcquisitionEngine eng_; private boolean finished_ = false; private boolean promptToSave_ = true; private String name_; private long lastDisplayTime_; private int lastFrameShown_ = 0; private int lastSliceShown_ = 0; private int lastPositionShown_ = 0; private boolean updating_ = false; private int[] channelInitiated_; private int preferredSlice_ = -1; private int preferredPosition_ = -1; private int preferredChannel_ = -1; private Timer preferredPositionTimer_; private int numComponents_; private ImagePlus hyperImage_; private ScrollbarWithLabel pSelector_; private ScrollbarWithLabel tSelector_; private ScrollbarWithLabel zSelector_; private ScrollbarWithLabel cSelector_; private DisplayControls controls_; public AcquisitionVirtualStack virtualStack_; private boolean simple_ = false; private boolean mda_ = false; //flag if display corresponds to MD acquisition private MetadataPanel mdPanel_; private boolean newDisplay_ = true; //used for autostretching on window opening private double framesPerSec_ = 7; private Timer zAnimationTimer_; private Timer tAnimationTimer_; private Component zIcon_, pIcon_, tIcon_, cIcon_; private HashMap<Integer, Integer> zStackMins_; private HashMap<Integer, Integer> zStackMaxes_; /* This interface and the following two classes * allow us to manipulate the dimensions * in an ImagePlus without it throwing conniptions. */ public interface IMMImagePlus { public int getNChannelsUnverified(); public int getNSlicesUnverified(); public int getNFramesUnverified(); public void setNChannelsUnverified(int nChannels); public void setNSlicesUnverified(int nSlices); public void setNFramesUnverified(int nFrames); public void drawWithoutUpdate(); } public class MMCompositeImage extends CompositeImage implements IMMImagePlus { public VirtualAcquisitionDisplay display_; private boolean updatingImage_, settingMode_, settingLut_; MMCompositeImage(ImagePlus imgp, int type, VirtualAcquisitionDisplay disp) { super(imgp, type); display_ = disp; } @Override public String getTitle() { return name_; } private void superReset() { super.reset(); } @Override public void reset() { if (SwingUtilities.isEventDispatchThread()) { super.reset(); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { superReset(); } }); } } /* * ImageJ workaround: the following two functions set the currentChannel field to -1, which can lead to a null * pointer exception if the function is called while CompositeImage.updateImage is also running on a different * Thread. So we make sure they are all on the EDT so this never happens */ @Override public synchronized void setMode(final int mode) { Runnable runnable = new Runnable() { @Override public void run() { superSetMode(mode); } }; invokeLaterIfNotEDT(runnable); } private void superSetMode(int mode) { super.setMode(mode); } @Override public synchronized void setChannelLut(final LUT lut) { Runnable runnable = new Runnable() { @Override public void run() { superSetLut(lut); } }; invokeLaterIfNotEDT(runnable); } private void superSetLut(LUT lut) { super.setChannelLut(lut); } @Override public synchronized void updateImage() { Runnable runnable = new Runnable() { @Override public void run() { superUpdateImage(); } }; invokeLaterIfNotEDT(runnable); } private void superUpdateImage() { super.updateImage(); } @Override public int getImageStackSize() { return super.nChannels * super.nSlices * super.nFrames; } @Override public int getStackSize() { return getImageStackSize(); } @Override public int getNChannelsUnverified() { return super.nChannels; } @Override public int getNSlicesUnverified() { return super.nSlices; } @Override public int getNFramesUnverified() { return super.nFrames; } @Override public void setNChannelsUnverified(int nChannels) { super.nChannels = nChannels; } @Override public void setNSlicesUnverified(int nSlices) { super.nSlices = nSlices; } @Override public void setNFramesUnverified(int nFrames) { super.nFrames = nFrames; } private void superDraw() { super.draw(); } @Override public void draw() { Runnable runnable = new Runnable() { public void run() { imageChangedUpdate(); superDraw(); } }; invokeLaterIfNotEDT(runnable); } @Override public void drawWithoutUpdate() { super.getWindow().getCanvas().setImageUpdated(); super.draw(); } } public class MMImagePlus extends ImagePlus implements IMMImagePlus { public VirtualAcquisitionDisplay display_; MMImagePlus(String title, ImageStack stack, VirtualAcquisitionDisplay disp) { super(title, stack); display_ = disp; } @Override public String getTitle() { return name_; } @Override public int getImageStackSize() { return super.nChannels * super.nSlices * super.nFrames; } @Override public int getStackSize() { return getImageStackSize(); } @Override public int getNChannelsUnverified() { return super.nChannels; } @Override public int getNSlicesUnverified() { return super.nSlices; } @Override public int getNFramesUnverified() { return super.nFrames; } @Override public void setNChannelsUnverified(int nChannels) { super.nChannels = nChannels; } @Override public void setNSlicesUnverified(int nSlices) { super.nSlices = nSlices; } @Override public void setNFramesUnverified(int nFrames) { super.nFrames = nFrames; } private void superDraw() { super.draw(); } @Override public void draw() { if (!SwingUtilities.isEventDispatchThread()) { Runnable onEDT = new Runnable() { public void run() { imageChangedUpdate(); superDraw(); } }; SwingUtilities.invokeLater(onEDT); } else { imageChangedUpdate(); super.draw(); } } @Override public void drawWithoutUpdate() { //ImageJ requires this super.getWindow().getCanvas().setImageUpdated(); super.draw(); } } public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng) { this(imageCache, eng, WindowManager.getUniqueName("Untitled")); } public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng, String name) { name_ = name; imageCache_ = imageCache; eng_ = eng; pSelector_ = createPositionScrollbar(); imageCache_.setDisplay(this); mda_ = eng != null; zStackMins_ = new HashMap<Integer, Integer>(); zStackMaxes_ = new HashMap<Integer, Integer>(); } //used for snap and live public VirtualAcquisitionDisplay(ImageCache imageCache, String name) throws MMScriptException { simple_ = true; imageCache_ = imageCache; name_ = name; System.out.println(); imageCache_.setDisplay(this); mda_ = false; } private void invokeAndWaitIfNotEDT(Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { try { SwingUtilities.invokeAndWait(runnable); } catch (InterruptedException ex) { ReportingUtils.logError(ex); } catch (InvocationTargetException ex) { System.out.println(ex.getCause()); } } } private void invokeLaterIfNotEDT(Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { SwingUtilities.invokeLater(runnable); } } private void startup(JSONObject firstImageMetadata) { mdPanel_ = MMStudioMainFrame.getInstance().getMetadataPanel(); JSONObject summaryMetadata = getSummaryMetadata(); int numSlices = 1; int numFrames = 1; int numChannels = 1; int numGrayChannels; int numPositions = 0; int width = 0; int height = 0; int numComponents = 1; try { if (firstImageMetadata != null) { width = MDUtils.getWidth(firstImageMetadata); height = MDUtils.getHeight(firstImageMetadata); } else { width = MDUtils.getWidth(summaryMetadata); height = MDUtils.getHeight(summaryMetadata); } numSlices = Math.max(summaryMetadata.getInt("Slices"), 1); numFrames = Math.max(summaryMetadata.getInt("Frames"), 1); int imageChannelIndex; try { imageChannelIndex = MDUtils.getChannelIndex(firstImageMetadata); } catch (Exception e) { imageChannelIndex = -1; } numChannels = Math.max(1 + imageChannelIndex, Math.max(summaryMetadata.getInt("Channels"), 1)); numPositions = Math.max(summaryMetadata.getInt("Positions"), 0); numComponents = Math.max(MDUtils.getNumberOfComponents(summaryMetadata), 1); } catch (Exception e) { ReportingUtils.showError(e); } numComponents_ = numComponents; numGrayChannels = numComponents_ * numChannels; channelInitiated_ = new int[numGrayChannels]; if (imageCache_.getDisplayAndComments() == null || imageCache_.getDisplayAndComments().isNull("Channels")) { imageCache_.setDisplayAndComments(getDisplaySettingsFromSummary(summaryMetadata)); } int type = 0; try { if (firstImageMetadata != null) { type = MDUtils.getSingleChannelType(firstImageMetadata); } else { type = MDUtils.getSingleChannelType(summaryMetadata); } } catch (Exception ex) { ReportingUtils.showError(ex, "Unable to determine acquisition type."); } virtualStack_ = new AcquisitionVirtualStack(width, height, type, null, imageCache_, numGrayChannels * numSlices * numFrames, this); if (summaryMetadata.has("PositionIndex")) { try { virtualStack_.setPositionIndex(MDUtils.getPositionIndex(summaryMetadata)); } catch (Exception ex) { ReportingUtils.logError(ex); } } if (simple_) { controls_ = new SimpleWindowControls(this); } else { controls_ = new HyperstackControls(this); } hyperImage_ = createHyperImage(createMMImagePlus(virtualStack_), numGrayChannels, numSlices, numFrames, virtualStack_, controls_); applyPixelSizeCalibration(hyperImage_); mdPanel_.setup(null); createWindow(); //Make sure contrast panel sets up correctly here windowToFront(); setupMetadataPanel(); cSelector_ = getSelector("c"); if (!simple_) { tSelector_ = getSelector("t"); zSelector_ = getSelector("z"); if (zSelector_ != null) { zSelector_.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { preferredSlice_ = zSelector_.getValue(); } }); } if (cSelector_ != null) { cSelector_.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { preferredChannel_ = cSelector_.getValue(); } }); } if (imageCache_.lastAcquiredFrame() > 1) { setNumFrames(1 + imageCache_.lastAcquiredFrame()); } else { setNumFrames(1); } configureAnimationControls(); //cant use these function because of an imageJ bug // setNumSlices(numSlices); setNumPositions(numPositions); } updateAndDraw(); updateWindowTitleAndStatus(); forcePainting(); } private void forcePainting() { Runnable forcePaint = new Runnable() { public void run() { if (zIcon_ != null) { zIcon_.paint(zIcon_.getGraphics()); } if (tIcon_ != null) { tIcon_.paint(tIcon_.getGraphics()); } if (cIcon_ != null) { cIcon_.paint(cIcon_.getGraphics()); } if (controls_ != null) { controls_.paint(controls_.getGraphics()); } if (pIcon_ != null && pIcon_.isValid()) { pIcon_.paint(pIcon_.getGraphics()); } } }; if (SwingUtilities.isEventDispatchThread()) { forcePaint.run(); } else { try { SwingUtilities.invokeAndWait(forcePaint); } catch (Exception ex) { ReportingUtils.logError(ex); } } } private void animateSlices(boolean animate) { if (zAnimationTimer_ == null) { zAnimationTimer_ = new Timer((int) (1000.0 / framesPerSec_), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int slice = hyperImage_.getSlice(); if (slice >= zSelector_.getMaximum() - 1) { hyperImage_.setPosition(hyperImage_.getChannel(), 1, hyperImage_.getFrame()); } else { hyperImage_.setPosition(hyperImage_.getChannel(), slice + 1, hyperImage_.getFrame()); } } }); } if (!animate) { zAnimationTimer_.stop(); refreshAnimationIcons(); return; } if (tAnimationTimer_ != null) { animateFrames(false); } zAnimationTimer_.setDelay((int) (1000.0 / framesPerSec_)); zAnimationTimer_.start(); refreshAnimationIcons(); } private void animateFrames(boolean animate) { if (tAnimationTimer_ == null) { tAnimationTimer_ = new Timer((int) (1000.0 / framesPerSec_), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int frame = hyperImage_.getFrame(); if (frame >= tSelector_.getMaximum() - 1) { hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), 1); } else { hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), frame + 1); } } }); } if (!animate) { tAnimationTimer_.stop(); refreshAnimationIcons(); return; } if (zAnimationTimer_ != null) { animateSlices(false); } tAnimationTimer_.setDelay((int) (1000.0 / framesPerSec_)); tAnimationTimer_.start(); refreshAnimationIcons(); } private void refreshAnimationIcons() { if (zIcon_ != null) { zIcon_.repaint(); } if (tIcon_ != null) { tIcon_.repaint(); } } private void configureAnimationControls() { if (zIcon_ != null) { zIcon_.addMouseListener(new MouseListener() { public void mousePressed(MouseEvent e) { animateSlices(zAnimationTimer_ == null || !zAnimationTimer_.isRunning()); } public void mouseClicked(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }); } if (tIcon_ != null) { tIcon_.addMouseListener(new MouseListener() { public void mousePressed(MouseEvent e) { animateFrames(tAnimationTimer_ == null || !tAnimationTimer_.isRunning()); } public void mouseClicked(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }); } } /** * Allows bypassing the prompt to Save * @param promptToSave boolean flag */ public void promptToSave(boolean promptToSave) { promptToSave_ = promptToSave; } /* * Method required by ImageCacheListener */ @Override public void imageReceived(final TaggedImage taggedImage) { if (eng_ != null) { updateDisplay(taggedImage, false); } } /* * Method required by ImageCacheListener */ @Override public void imagingFinished(String path) { updateDisplay(null, true); updateAndDraw(); if (eng_ != null && !eng_.abortRequested()) { updateWindowTitleAndStatus(); } } private void updateDisplay(TaggedImage taggedImage, boolean finalUpdate) { try { long t = System.currentTimeMillis(); JSONObject tags; if (taggedImage != null) { tags = taggedImage.tags; } else { tags = imageCache_.getLastImageTags(); } if (tags == null) { return; } int frame = MDUtils.getFrameIndex(tags); int ch = MDUtils.getChannelIndex(tags); int slice = MDUtils.getSliceIndex(tags); int position = MDUtils.getPositionIndex(tags); boolean show = finalUpdate || frame == 0 || (Math.abs(t - lastDisplayTime_) > 30) || (ch == getNumChannels() - 1 && lastFrameShown_ == frame && lastSliceShown_ == slice && lastPositionShown_ == position) || (slice == getNumSlices() - 1 && frame == 0 && position == 0 && ch == getNumChannels() - 1); if (show) { showImage(tags, true); lastFrameShown_ = frame; lastSliceShown_ = slice; lastPositionShown_ = position; lastDisplayTime_ = t; forceImagePaint(); } } catch (Exception e) { ReportingUtils.logError(e); } } private void forceImagePaint() { hyperImage_.getWindow().getCanvas().paint(hyperImage_.getWindow().getCanvas().getGraphics()); } public int rgbToGrayChannel(int channelIndex) { try { if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) { return channelIndex * 3; } return channelIndex; } catch (Exception ex) { ReportingUtils.logError(ex); return 0; } } public int grayToRGBChannel(int grayIndex) { try { if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) { return grayIndex / 3; } return grayIndex; } catch (Exception ex) { ReportingUtils.logError(ex); return 0; } } public static JSONObject getDisplaySettingsFromSummary(JSONObject summaryMetadata) { try { JSONObject displaySettings = new JSONObject(); JSONArray chColors = MDUtils.getJSONArrayMember(summaryMetadata, "ChColors"); JSONArray chNames = MDUtils.getJSONArrayMember(summaryMetadata, "ChNames"); JSONArray chMaxes, chMins; if ( summaryMetadata.has("ChContrastMin")) { chMins = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMin"); } else { chMins = new JSONArray(); for (int i = 0; i < chNames.length(); i++) chMins.put(0); } if ( summaryMetadata.has("ChContrastMax")) { chMaxes = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMax"); } else { int max = 65536; if (summaryMetadata.has("BitDepth")) max = (int) (Math.pow(2, summaryMetadata.getInt("BitDepth"))-1); chMaxes = new JSONArray(); for (int i = 0; i < chNames.length(); i++) chMaxes.put(max); } int numComponents = MDUtils.getNumberOfComponents(summaryMetadata); JSONArray channels = new JSONArray(); if (numComponents > 1) //RGB { int rgbChannelBitDepth = summaryMetadata.getString("PixelType").endsWith("32") ? 8 : 16; for (int k = 0; k < 3; k++) { JSONObject channelObject = new JSONObject(); channelObject.put("Color", rgb[k].getRGB()); channelObject.put("Name", rgbNames[k]); channelObject.put("Gamma", 1.0); channelObject.put("Min", 0); channelObject.put("Max", Math.pow(2, rgbChannelBitDepth) - 1); channels.put(channelObject); } } else { for (int k = 0; k < chNames.length(); ++k) { String name = (String) chNames.get(k); int color = chColors.getInt(k); int min = chMins.getInt(k); int max = chMaxes.getInt(k); JSONObject channelObject = new JSONObject(); channelObject.put("Color", color); channelObject.put("Name", name); channelObject.put("Gamma", 1.0); channelObject.put("Min", min); channelObject.put("Max", max); channels.put(channelObject); } } displaySettings.put("Channels", channels); JSONObject comments = new JSONObject(); String summary = ""; try { summary = summaryMetadata.getString("Comment"); } catch (JSONException ex) { summaryMetadata.put("Comment", ""); } comments.put("Summary", summary); displaySettings.put("Comments", comments); return displaySettings; } catch (Exception e) { ReportingUtils.showError("Error creating display settigns from summary metadata"); return null; } } /** * Sets ImageJ pixel size calibration * @param hyperImage */ private void applyPixelSizeCalibration(final ImagePlus hyperImage) { try { double pixSizeUm = getSummaryMetadata().getDouble("PixelSize_um"); if (pixSizeUm > 0) { Calibration cal = new Calibration(); cal.setUnit("um"); cal.pixelWidth = pixSizeUm; cal.pixelHeight = pixSizeUm; hyperImage.setCalibration(cal); } } catch (JSONException ex) { // no pixelsize defined. Nothing to do } } private void setNumPositions(int n) { if (simple_) { return; } pSelector_.setMinimum(0); pSelector_.setMaximum(n); ImageWindow win = hyperImage_.getWindow(); if (n > 1 && pSelector_.getParent() == null) { win.add(pSelector_, win.getComponentCount() - 1); } else if (n <= 1 && pSelector_.getParent() != null) { win.remove(pSelector_); } win.pack(); } private void setNumFrames(int n) { if (simple_) { return; } if (tSelector_ != null) { //ImageWindow win = hyperImage_.getWindow(); ((IMMImagePlus) hyperImage_).setNFramesUnverified(n); tSelector_.setMaximum(n + 1); // JavaUtils.setRestrictedFieldValue(win, StackWindow.class, "nFrames", n); } } private void setNumSlices(int n) { if (simple_) { return; } if (zSelector_ != null) { ((IMMImagePlus) hyperImage_).setNSlicesUnverified(n); zSelector_.setMaximum(n + 1); } } private void setNumChannels(int n) { if (cSelector_ != null) { ((IMMImagePlus) hyperImage_).setNChannelsUnverified(n); cSelector_.setMaximum(n); } } public ImagePlus getHyperImage() { return hyperImage_; } public int getStackSize() { if (hyperImage_ == null) { return -1; } int s = hyperImage_.getNSlices(); int c = hyperImage_.getNChannels(); int f = hyperImage_.getNFrames(); if ((s > 1 && c > 1) || (c > 1 && f > 1) || (f > 1 && s > 1)) { return s * c * f; } return Math.max(Math.max(s, c), f); } private void imageChangedWindowUpdate() { if (hyperImage_ != null && hyperImage_.isVisible()) { TaggedImage ti = virtualStack_.getTaggedImage(hyperImage_.getCurrentSlice()); if (ti != null) { controls_.newImageUpdate(ti.tags); } } } public void updateAndDraw() { if (!updating_) { updating_ = true; setupMetadataPanel(); if (hyperImage_ != null && hyperImage_.isVisible()) { hyperImage_.updateAndDraw(); } updating_ = false; } } public void updateWindowTitleAndStatus() { if (simple_) { int mag = (int) (100 * hyperImage_.getCanvas().getMagnification()); String title = hyperImage_.getTitle() + " ("+mag+"%)"; hyperImage_.getWindow().setTitle(title); return; } if (controls_ == null) { return; } String status = ""; final AcquisitionEngine eng = eng_; if (eng != null) { if (acquisitionIsRunning()) { if (!abortRequested()) { controls_.acquiringImagesUpdate(true); if (isPaused()) { status = "paused"; } else { status = "running"; } } else { controls_.acquiringImagesUpdate(false); status = "interrupted"; } } else { controls_.acquiringImagesUpdate(false); if (!status.contentEquals("interrupted")) { if (eng.isFinished()) { status = "finished"; eng_ = null; } } } status += ", "; if (eng.isFinished()) { eng_ = null; finished_ = true; } } else { if (finished_ == true) { status = "finished, "; } controls_.acquiringImagesUpdate(false); } if (isDiskCached()) { status += "on disk"; } else { status += "not yet saved"; } controls_.imagesOnDiskUpdate(imageCache_.getDiskLocation() != null); String path = isDiskCached() ? new File(imageCache_.getDiskLocation()).getName() : name_; if (hyperImage_.isVisible()) { int mag = (int) (100 * hyperImage_.getCanvas().getMagnification()); hyperImage_.getWindow().setTitle(path + " (" + status + ") (" + mag + "%)" ); } } private void windowToFront() { if (hyperImage_ == null || hyperImage_.getWindow() == null) { return; } hyperImage_.getWindow().toFront(); } private void setupMetadataPanel() { if (hyperImage_ == null || hyperImage_.getWindow() == null) { return; } //call this explicitly because it isn't fired immediately mdPanel_.setup(hyperImage_.getWindow()); } /** * Displays tagged image in the multi-D viewer * Will wait for the screen update * * @param taggedImg * @throws Exception */ public void showImage(TaggedImage taggedImg) throws Exception { showImage(taggedImg, true); } /** * Displays tagged image in the multi-D viewer * Optionally waits for the display to draw the image * * * @param taggedImg * @throws Exception */ public void showImage(TaggedImage taggedImg, boolean waitForDisplay) throws InterruptedException, InvocationTargetException { showImage(taggedImg.tags, waitForDisplay); } public void showImage(JSONObject tags, boolean waitForDisplay) throws InterruptedException, InvocationTargetException { updateWindowTitleAndStatus(); if (tags == null) { return; } if (hyperImage_ == null) { startup(tags); } final boolean framesAnimated = isTAnimated(), slicesAnimated = isZAnimated(); final int animatedFrameIndex = hyperImage_.getFrame(), animatedSliceIndex = hyperImage_.getSlice(); if (framesAnimated || slicesAnimated) { animateFrames(false); animateSlices(false); } int channel = 0, frame = 0, slice = 0, position = 0, superChannel = 0; try { frame = MDUtils.getFrameIndex(tags); slice = MDUtils.getSliceIndex(tags); channel = MDUtils.getChannelIndex(tags); position = MDUtils.getPositionIndex(tags); superChannel = this.rgbToGrayChannel(MDUtils.getChannelIndex(tags)); } catch (Exception ex) { ReportingUtils.logError(ex); } //make sure pixels get properly set if (hyperImage_ != null && frame == 0) { IMMImagePlus img = (IMMImagePlus) hyperImage_; if (img.getNChannelsUnverified() == 1) { if (img.getNSlicesUnverified() == 1) { hyperImage_.getProcessor().setPixels(virtualStack_.getPixels(1)); } } else if (hyperImage_ instanceof MMCompositeImage) { //reset rebuilds each of the channel ImageProcessors with the correct pixels //from AcquisitionVirtualStack MMCompositeImage ci = ((MMCompositeImage) hyperImage_); ci.reset(); //This line is neccessary for image processor to have correct pixels in grayscale mode ci.getProcessor().setPixels(virtualStack_.getPixels(ci.getCurrentSlice())); } } else if (hyperImage_ instanceof MMCompositeImage) { MMCompositeImage ci = ((MMCompositeImage) hyperImage_); ci.reset(); } if (cSelector_ != null) { if (cSelector_.getMaximum() <= (1 + superChannel)) { this.setNumChannels(1 + superChannel); ((CompositeImage) hyperImage_).reset(); //JavaUtils.invokeRestrictedMethod(hyperImage_, CompositeImage.class, // "setupLuts", 1 + superChannel, Integer.TYPE); } } initializeContrast(channel, slice); if (!simple_) { if (tSelector_ != null) { if (tSelector_.getMaximum() <= (1 + frame)) { this.setNumFrames(1 + frame); } } if (position + 1 >= getNumPositions()) { setNumPositions(position + 1); } setPosition(position); hyperImage_.setPosition(1 + superChannel, 1 + slice, 1 + frame); } Runnable updateAndDraw = new Runnable() { public void run() { updateAndDraw(); restartAnimationAfterShowing(animatedFrameIndex, animatedSliceIndex, framesAnimated, slicesAnimated); } }; if (!SwingUtilities.isEventDispatchThread()) { if (waitForDisplay) { SwingUtilities.invokeAndWait(updateAndDraw); } else { SwingUtilities.invokeLater(updateAndDraw); } } else { updateAndDraw(); restartAnimationAfterShowing(animatedFrameIndex, animatedSliceIndex, framesAnimated, slicesAnimated); } setPreferredScrollbarPositions(); } /** * If animation was running prior to showImage, restarts it with sliders at appropriate positions */ private void restartAnimationAfterShowing(int frame, int slice, boolean framesAnimated, boolean slicesAnimated) { if (framesAnimated) { hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), frame+1); animateFrames(true); } else if (slicesAnimated) { hyperImage_.setPosition(hyperImage_.getChannel(), slice+1, hyperImage_.getFrame()); animateSlices(true); } } /* * Live/snap should load window contrast settings * MDA should autoscale on frist image * Opening dataset should load from disoplay and comments */ private void initializeContrast(final int channel, final int slice) { Runnable autoscaleOrLoadContrast = new Runnable() { public void run() { if (!newDisplay_) { return; } if (simple_) { //Snap/live if (hyperImage_ instanceof MMCompositeImage && ((MMCompositeImage) hyperImage_).getNChannelsUnverified() - 1 != channel) { return; } mdPanel_.loadSimpleWinContrastWithoutDraw(imageCache_, hyperImage_); } else if (mda_) { //Multi D acquisition IMMImagePlus immImg = ((IMMImagePlus) hyperImage_); if (immImg.getNSlicesUnverified() > 1) { //Z stacks mdPanel_.autoscaleOverStackWithoutDraw(imageCache_, hyperImage_, channel, zStackMins_, zStackMaxes_); if (channel != immImg.getNChannelsUnverified() - 1 || slice != immImg.getNSlicesUnverified() - 1) { return; //don't set new display to false until all channels autscaled } } else { //No z stacks mdPanel_.autoscaleWithoutDraw(imageCache_, hyperImage_); if (immImg.getNChannelsUnverified() - 1 != channel) { return; } } } else //Acquire button if (hyperImage_ instanceof MMCompositeImage) { if (((MMCompositeImage) hyperImage_).getNChannelsUnverified() - 1 != channel) { return; } mdPanel_.autoscaleWithoutDraw(imageCache_, hyperImage_); } else { mdPanel_.autoscaleWithoutDraw(imageCache_, hyperImage_); // else do nothing because contrast automatically loaded from cache } newDisplay_ = false; } }; if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(autoscaleOrLoadContrast); } else { autoscaleOrLoadContrast.run(); } } private void setPreferredScrollbarPositions() { if (this.acquisitionIsRunning()) { long nextImageTime = eng_.getNextWakeTime(); if (System.nanoTime() / 1000000 - nextImageTime < -1000) { //1 sec or more until next start if (preferredPositionTimer_ == null) { preferredPositionTimer_ = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { IMMImagePlus ip = ((IMMImagePlus) hyperImage_); int c = hyperImage_.getChannel(), s = hyperImage_.getSlice(), f = hyperImage_.getFrame(); hyperImage_.setPosition(preferredChannel_ == -1 ? c : preferredChannel_, preferredSlice_ == -1 ? s : preferredSlice_, f); if (pSelector_ != null && preferredPosition_ > -1) { if (eng_.getAcqOrderMode() != AcqOrderMode.POS_TIME_CHANNEL_SLICE && eng_.getAcqOrderMode() != AcqOrderMode.POS_TIME_SLICE_CHANNEL) { setPosition(preferredPosition_); } } preferredPositionTimer_.stop();; } }); } if (preferredPositionTimer_.isRunning()) { return; } preferredPositionTimer_.start(); } } } private void updatePosition(int p) { if (simple_) { return; } virtualStack_.setPositionIndex(p); if (!hyperImage_.isComposite()) { Object pixels = virtualStack_.getPixels(hyperImage_.getCurrentSlice()); hyperImage_.getProcessor().setPixels(pixels); } else { CompositeImage ci = (CompositeImage) hyperImage_; if (ci.getMode() == CompositeImage.COMPOSITE) { for (int i = 0; i < ((MMCompositeImage) ci).getNChannelsUnverified(); i++) { ci.getProcessor(i + 1).setPixels(virtualStack_.getPixels( ci.getCurrentSlice() - ci.getChannel() + i + 1)); } } ci.getProcessor().setPixels(virtualStack_.getPixels(hyperImage_.getCurrentSlice())); } //need to call this even though updateAndDraw also calls it to get autostretch to work properly imageChangedUpdate(); updateAndDraw(); } public void setPosition(int p) { if (simple_) { return; } pSelector_.setValue(p); } public void setSliceIndex(int i) { if (simple_) { return; } final int f = hyperImage_.getFrame(); final int c = hyperImage_.getChannel(); hyperImage_.setPosition(c, i + 1, f); } public int getSliceIndex() { return hyperImage_.getSlice() - 1; } boolean pause() { if (eng_ != null) { if (eng_.isPaused()) { eng_.setPause(false); } else { eng_.setPause(true); } updateWindowTitleAndStatus(); return (eng_.isPaused()); } return false; } boolean abort() { if (eng_ != null) { if (eng_.abortRequest()) { updateWindowTitleAndStatus(); return true; } } return false; } public boolean acquisitionIsRunning() { if (eng_ != null) { return eng_.isAcquisitionRunning(); } else { return false; } } public long getNextWakeTime() { return eng_.getNextWakeTime(); } public boolean abortRequested() { if (eng_ != null) { return eng_.abortRequested(); } else { return false; } } private boolean isPaused() { if (eng_ != null) { return eng_.isPaused(); } else { return false; } } boolean saveAs() { String prefix; String root; for (;;) { File f = FileDialogs.save(hyperImage_.getWindow(), "Please choose a location for the data set", MMStudioMainFrame.MM_DATA_SET); if (f == null) // Canceled. { return false; } prefix = f.getName(); root = new File(f.getParent()).getAbsolutePath(); if (f.exists()) { ReportingUtils.showMessage(prefix + " is write only! Please choose another name."); } else { break; } } TaggedImageStorageDiskDefault newFileManager = new TaggedImageStorageDiskDefault(root + "/" + prefix, true, getSummaryMetadata()); imageCache_.saveAs(newFileManager, mda_); MMStudioMainFrame.getInstance().setAcqDirectory(root); updateWindowTitleAndStatus(); return true; } final public MMImagePlus createMMImagePlus(AcquisitionVirtualStack virtualStack) { MMImagePlus img = new MMImagePlus(imageCache_.getDiskLocation(), virtualStack, this); FileInfo fi = new FileInfo(); fi.width = virtualStack.getWidth(); fi.height = virtualStack.getHeight(); fi.fileName = virtualStack.getDirectory(); fi.url = null; img.setFileInfo(fi); return img; } final public ImagePlus createHyperImage(MMImagePlus mmIP, int channels, int slices, int frames, final AcquisitionVirtualStack virtualStack, DisplayControls hc) { final ImagePlus hyperImage; mmIP.setNChannelsUnverified(channels); mmIP.setNFramesUnverified(frames); mmIP.setNSlicesUnverified(slices); if (channels > 1) { hyperImage = new MMCompositeImage(mmIP, CompositeImage.COMPOSITE, this); hyperImage.setOpenAsHyperStack(true); } else { hyperImage = mmIP; mmIP.setOpenAsHyperStack(true); } return hyperImage; } public void liveModeEnabled(boolean enabled) { if (simple_) { controls_.acquiringImagesUpdate(enabled); } } private void createWindow() { final DisplayWindow win = new DisplayWindow(hyperImage_); win.getCanvas().addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent me) { } //used to store preferred zoom public void mousePressed(MouseEvent me) { int id = Toolbar.getToolId(); int currentLength = (win.getSize().width + win.getSize().height) / 2; if (id == 11) {//zoom tool selected if (me.getButton() == MouseEvent.BUTTON1) { //Zoom in prefs_.putInt(PREF_WIN_LENGTH, Math.max(currentLength, 512)); } else if (me.getButton() == MouseEvent.BUTTON3) { //Zoom out prefs_.putInt(PREF_WIN_LENGTH, Math.max(currentLength, 512)); } } updateWindowTitleAndStatus(); } //updates the histogram after an ROI is drawn public void mouseReleased(MouseEvent me) { mdPanel_.refresh(); } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } }); win.setBackground(MMStudioMainFrame.getInstance().getBackgroundColor()); MMStudioMainFrame.getInstance().addMMBackgroundListener(win); win.add(controls_); win.pack(); //Set magnification zoomToPreferredSize(win); if (simple_) { win.setLocation(prefs_.getInt(SIMPLE_WIN_X, 0), prefs_.getInt(SIMPLE_WIN_Y, 0)); } } private void zoomToPreferredSize(DisplayWindow win) { int prefLength = prefs_.getInt(PREF_WIN_LENGTH, 512); int winLength = (int) Math.sqrt(win.getSize().width * win.getSize().height); double percentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength)); ImageCanvas canvas = win.getCanvas(); if (winLength < prefLength) { while (winLength < prefLength) { percentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength)); canvas.zoomIn(canvas.getSize().width / 2, canvas.getSize().height / 2); int newWinLength = (int) Math.sqrt(win.getSize().width * win.getSize().height); if (newWinLength == winLength) break; winLength = newWinLength; } double newPercentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength)); if (newPercentDiff > percentDiff) { canvas.zoomOut(canvas.getSize().width / 2, canvas.getSize().height / 2); } } else if (winLength > prefLength) { while (winLength > prefLength) { percentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength)); canvas.zoomOut(canvas.getSize().width / 2, canvas.getSize().height / 2); int newWinLength = (int) Math.sqrt(win.getSize().width * win.getSize().height); if (newWinLength == winLength) break; winLength = newWinLength; } double newPercentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength)); if (newPercentDiff > percentDiff) { canvas.zoomIn(canvas.getSize().width / 2, canvas.getSize().height / 2); } } Rectangle rect = canvas.getSrcRect(); if (rect != null) { while (rect.width < canvas.getImage().getWidth() || rect.height < canvas.getImage().getHeight()) { if (rect.width > 0.9 * canvas.getImage().getWidth() && rect.height > 0.9 * canvas.getImage().getHeight()) { canvas.zoomOut(canvas.getSize().width / 2, canvas.getSize().height / 2); canvas.zoomIn(canvas.getSize().width / 2, canvas.getSize().height / 2); break; } else { canvas.zoomOut(canvas.getSize().width / 2, canvas.getSize().height / 2); } rect = canvas.getSrcRect(); if (rect == null) { break; } } } } private ScrollbarWithLabel getSelector(String label) { // label should be "t", "z", or "c" ScrollbarWithLabel selector = null; ImageWindow win = hyperImage_.getWindow(); int slices = ((IMMImagePlus) hyperImage_).getNSlicesUnverified(); int frames = ((IMMImagePlus) hyperImage_).getNFramesUnverified(); int channels = ((IMMImagePlus) hyperImage_).getNChannelsUnverified(); if (win instanceof StackWindow) { try { //ImageJ bug workaround if (frames > 1 && slices == 1 && channels == 1 && label.equals("t")) { selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, "zSelector"); } else { selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, label + "Selector"); } } catch (NoSuchFieldException ex) { selector = null; ReportingUtils.logError(ex); } } //replace default icon with custom one if (selector != null) { try { Component icon = (Component) JavaUtils.getRestrictedFieldValue( selector, ScrollbarWithLabel.class, "icon"); selector.remove(icon); } catch (NoSuchFieldException ex) { ReportingUtils.logError(ex); } ScrollbarIcon newIcon = new ScrollbarIcon(label.charAt(0), this); if (label.equals("z")) { zIcon_ = newIcon; } else if (label.equals("t")) { tIcon_ = newIcon; } else if (label.equals("c")) { cIcon_ = newIcon; } selector.add(newIcon, BorderLayout.WEST); selector.invalidate(); selector.validate(); } return selector; } private ScrollbarWithLabel createPositionScrollbar() { final ScrollbarWithLabel pSelector = new ScrollbarWithLabel(null, 1, 1, 1, 2, 'p') { @Override public void setValue(int v) { if (this.getValue() != v) { super.setValue(v); updatePosition(v); } } }; // prevents scroll bar from blinking on Windows: pSelector.setFocusable(false); pSelector.setUnitIncrement(1); pSelector.setBlockIncrement(1); pSelector.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { updatePosition(pSelector.getValue()); preferredPosition_ = pSelector_.getValue(); } }); if (pSelector != null) { try { Component icon = (Component) JavaUtils.getRestrictedFieldValue( pSelector, ScrollbarWithLabel.class, "icon"); pSelector.remove(icon); } catch (NoSuchFieldException ex) { ReportingUtils.logError(ex); } pIcon_ = new ScrollbarIcon('p', this); pSelector.add(pIcon_, BorderLayout.WEST); pSelector.invalidate(); pSelector.validate(); } return pSelector; } public JSONObject getCurrentMetadata() { try { if (hyperImage_ != null) { TaggedImage image = virtualStack_.getTaggedImage(hyperImage_.getCurrentSlice()); if (image != null) { return image.tags; } else { return null; } } else { return null; } } catch (NullPointerException ex) { return null; } } public int getCurrentPosition() { return virtualStack_.getPositionIndex(); } public int getNumSlices() { if (simple_) { return 1; } return ((IMMImagePlus) hyperImage_).getNSlicesUnverified(); } public int getNumFrames() { if (simple_) { return 1; } return ((IMMImagePlus) hyperImage_).getNFramesUnverified(); } public int getNumPositions() { if (simple_) { return 1; } return pSelector_.getMaximum(); } public ImagePlus getImagePlus() { return hyperImage_; } public ImageCache getImageCache() { return imageCache_; } public ImagePlus getImagePlus(int position) { ImagePlus iP = new ImagePlus(); iP.setStack(virtualStack_); iP.setDimensions(numComponents_ * getNumChannels(), getNumSlices(), getNumFrames()); iP.setFileInfo(hyperImage_.getFileInfo()); return iP; } public void setComment(String comment) throws MMScriptException { try { getSummaryMetadata().put("Comment", comment); } catch (Exception ex) { ReportingUtils.logError(ex); } } public final JSONObject getSummaryMetadata() { return imageCache_.getSummaryMetadata(); } public void close() { if (hyperImage_ != null) { //call this so when one window closes and is replaced by another //the md panel gets rid of the first before doing stuff with //the second if (WindowManager.getCurrentImage() == hyperImage_) { mdPanel_.setup(null); } hyperImage_.getWindow().windowClosing(null); hyperImage_.close(); } } public synchronized boolean windowClosed() { ImageWindow win = hyperImage_.getWindow(); return (win == null || win.isClosed()); } public void showFolder() { if (isDiskCached()) { try { File location = new File(imageCache_.getDiskLocation()); if (JavaUtils.isWindows()) { Runtime.getRuntime().exec("Explorer /n,/select," + location.getAbsolutePath()); } else if (JavaUtils.isMac()) { if (!location.isDirectory()) { location = location.getParentFile(); } Runtime.getRuntime().exec("open " + location.getAbsolutePath()); } } catch (IOException ex) { ReportingUtils.logError(ex); } } } public void setPlaybackFPS(double fps) { framesPerSec_ = fps; if (zAnimationTimer_ != null && zAnimationTimer_.isRunning()) { animateSlices(false); animateSlices(true); } else if (tAnimationTimer_ != null && tAnimationTimer_.isRunning()) { animateFrames(false); animateFrames(true); } } public double getPlaybackFPS() { return framesPerSec_; } public boolean isZAnimated() { if (zAnimationTimer_ != null && zAnimationTimer_.isRunning()) { return true; } return false; } public boolean isTAnimated() { if (tAnimationTimer_ != null && tAnimationTimer_.isRunning()) { return true; } return false; } public boolean isAnimated() { return isTAnimated() || isZAnimated(); } public String getSummaryComment() { return imageCache_.getComment(); } public void setSummaryComment(String comment) { imageCache_.setComment(comment); } void setImageComment(String comment) { imageCache_.setImageComment(comment, getCurrentMetadata()); } String getImageComment() { try { return imageCache_.getImageComment(getCurrentMetadata()); } catch (NullPointerException ex) { return ""; } } public boolean isDiskCached() { ImageCache imageCache = imageCache_; if (imageCache == null) { return false; } else { return imageCache.getDiskLocation() != null; } } public void show() { if (hyperImage_ == null) { startup(null); } hyperImage_.show(); hyperImage_.getWindow().toFront(); } public int getNumChannels() { return ((IMMImagePlus) hyperImage_).getNChannelsUnverified(); } public int getNumGrayChannels() { return getNumChannels(); } public void setWindowTitle(String name) { name_ = name; updateWindowTitleAndStatus(); } public boolean isSimpleDisplay() { return simple_; } public void displayStatusLine(String status) { controls_.setStatusLabel(status); } public void setChannelContrast(int channelIndex, int min, int max, double gamma) { mdPanel_.setChannelContrast(channelIndex, min, max, gamma); } private void imageChangedUpdate() { mdPanel_.imageChangedUpdate(hyperImage_, imageCache_); imageChangedWindowUpdate(); //used to update status line } public void refreshContrastPanel() { mdPanel_.refresh(); } public void drawWithoutUpdate() { if (hyperImage_ != null) { ((IMMImagePlus) hyperImage_).drawWithoutUpdate(); } } public class DisplayWindow extends StackWindow { private boolean windowClosingDone_ = false; private boolean closed_ = false; public DisplayWindow(ImagePlus ip) { super(ip); } @Override public boolean close() { windowClosing(null); return closed_; } @Override public void windowClosing(WindowEvent e) { if (windowClosingDone_) { return; } if (eng_ != null && eng_.isAcquisitionRunning()) { if (!abort()) { return; } } if (imageCache_.getDiskLocation() == null && promptToSave_) { int result = JOptionPane.showConfirmDialog(this, "This data set has not yet been saved.\n" + "Do you want to save it?", "Micro-Manager", JOptionPane.YES_NO_CANCEL_OPTION); if (result == JOptionPane.YES_OPTION) { if (!saveAs()) { return; } } else if (result == JOptionPane.CANCEL_OPTION) { return; } } //for some reason window focus listener doesn't always fire, so call //explicitly here mdPanel_.setup(null); if (simple_ && hyperImage_ != null && hyperImage_.getWindow() != null && hyperImage_.getWindow().getLocation() != null) { Point loc = hyperImage_.getWindow().getLocation(); prefs_.putInt(SIMPLE_WIN_X, loc.x); prefs_.putInt(SIMPLE_WIN_Y, loc.y); mdPanel_.saveContrastSettings(imageCache_); } if (imageCache_ != null) { imageCache_.close(); } if (!closed_) { try { super.close(); } catch (NullPointerException ex) { ReportingUtils.logError("Null pointer error in ImageJ code while closing window"); } } super.windowClosing(e); MMStudioMainFrame.getInstance().removeMMBackgroundListener(this); windowClosingDone_ = true; closed_ = true; } @Override public void windowClosed(WindowEvent E) { this.windowClosing(E); super.windowClosed(E); } @Override public void windowActivated(WindowEvent e) { if (!isClosed()) { super.windowActivated(e); } } @Override public void setAnimate(boolean b) { if (((IMMImagePlus) hyperImage_).getNFramesUnverified() > 1) { animateFrames(b); } else { animateSlices(b); } } @Override public boolean getAnimate() { return isAnimated(); } }; }
mmstudio/src/org/micromanager/acquisition/VirtualAcquisitionDisplay.java
/////////////////////////////////////////////////////////////////////////////// //FILE: VirtualAcquisitionDisplay.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio //----------------------------------------------------------------------------- // // AUTHOR: Henry Pinkard, [email protected], & Arthur Edelstein, 2010 // // COPYRIGHT: University of California, San Francisco, 2012 // // LICENSE: This file is distributed under the BSD license. // License text is included with the source distribution. // // This file is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // package org.micromanager.acquisition; import java.util.logging.Level; import java.util.logging.Logger; import org.micromanager.api.DisplayControls; import java.lang.reflect.InvocationTargetException; import org.micromanager.api.ImageCacheListener; import ij.ImageStack; import ij.process.LUT; import ij.CompositeImage; import ij.ImagePlus; import ij.WindowManager; import ij.gui.ImageCanvas; import ij.gui.ImageWindow; import ij.gui.ScrollbarWithLabel; import ij.gui.StackWindow; import ij.gui.Toolbar; import ij.io.FileInfo; import ij.measure.Calibration; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.*; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.prefs.Preferences; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.Timer; import mmcorej.TaggedImage; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.MMStudioMainFrame; import org.micromanager.api.AcquisitionEngine; import org.micromanager.api.ImageCache; import org.micromanager.utils.AcqOrderMode; import org.micromanager.utils.FileDialogs; import org.micromanager.utils.JavaUtils; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.ReportingUtils; public final class VirtualAcquisitionDisplay implements ImageCacheListener { public static VirtualAcquisitionDisplay getDisplay(ImagePlus imgp) { ImageStack stack = imgp.getStack(); if (stack instanceof AcquisitionVirtualStack) { return ((AcquisitionVirtualStack) stack).getVirtualAcquisitionDisplay(); } else { return null; } } final static Color[] rgb = {Color.red, Color.green, Color.blue}; final static String[] rgbNames = {"Red", "Blue", "Green"}; final ImageCache imageCache_; final Preferences prefs_ = Preferences.userNodeForPackage(this.getClass()); private static final String SIMPLE_WIN_X = "simple_x"; private static final String SIMPLE_WIN_Y = "simple_y"; private static final String PREF_WIN_LENGTH = "preferred_window_max_length"; private AcquisitionEngine eng_; private boolean finished_ = false; private boolean promptToSave_ = true; private String name_; private long lastDisplayTime_; private int lastFrameShown_ = 0; private int lastSliceShown_ = 0; private int lastPositionShown_ = 0; private boolean updating_ = false; private int[] channelInitiated_; private int preferredSlice_ = -1; private int preferredPosition_ = -1; private int preferredChannel_ = -1; private Timer preferredPositionTimer_; private int numComponents_; private ImagePlus hyperImage_; private ScrollbarWithLabel pSelector_; private ScrollbarWithLabel tSelector_; private ScrollbarWithLabel zSelector_; private ScrollbarWithLabel cSelector_; private DisplayControls controls_; public AcquisitionVirtualStack virtualStack_; private boolean simple_ = false; private boolean mda_ = false; //flag if display corresponds to MD acquisition private MetadataPanel mdPanel_; private boolean newDisplay_ = true; //used for autostretching on window opening private double framesPerSec_ = 7; private Timer zAnimationTimer_; private Timer tAnimationTimer_; private Component zIcon_, pIcon_, tIcon_, cIcon_; private HashMap<Integer, Integer> zStackMins_; private HashMap<Integer, Integer> zStackMaxes_; /* This interface and the following two classes * allow us to manipulate the dimensions * in an ImagePlus without it throwing conniptions. */ public interface IMMImagePlus { public int getNChannelsUnverified(); public int getNSlicesUnverified(); public int getNFramesUnverified(); public void setNChannelsUnverified(int nChannels); public void setNSlicesUnverified(int nSlices); public void setNFramesUnverified(int nFrames); public void drawWithoutUpdate(); } public class MMCompositeImage extends CompositeImage implements IMMImagePlus { public VirtualAcquisitionDisplay display_; private boolean updatingImage_, settingMode_, settingLut_; MMCompositeImage(ImagePlus imgp, int type, VirtualAcquisitionDisplay disp) { super(imgp, type); display_ = disp; } @Override public String getTitle() { return name_; } private void superReset() { super.reset(); } @Override public void reset() { if (SwingUtilities.isEventDispatchThread()) { super.reset(); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { superReset(); } }); } } /* * ImageJ workaround: the following two functions set the currentChannel field to -1, which can lead to a null * pointer exception if the function is called while CompositeImage.updateImage is also running on a different * Thread. So we make sure they are all on the EDT so this never happens */ @Override public synchronized void setMode(final int mode) { Runnable runnable = new Runnable() { @Override public void run() { superSetMode(mode); } }; invokeLaterIfNotEDT(runnable); } private void superSetMode(int mode) { super.setMode(mode); } @Override public synchronized void setChannelLut(final LUT lut) { Runnable runnable = new Runnable() { @Override public void run() { superSetLut(lut); } }; invokeLaterIfNotEDT(runnable); } private void superSetLut(LUT lut) { super.setChannelLut(lut); } @Override public synchronized void updateImage() { Runnable runnable = new Runnable() { @Override public void run() { superUpdateImage(); } }; invokeLaterIfNotEDT(runnable); } private void superUpdateImage() { super.updateImage(); } @Override public int getImageStackSize() { return super.nChannels * super.nSlices * super.nFrames; } @Override public int getStackSize() { return getImageStackSize(); } @Override public int getNChannelsUnverified() { return super.nChannels; } @Override public int getNSlicesUnverified() { return super.nSlices; } @Override public int getNFramesUnverified() { return super.nFrames; } @Override public void setNChannelsUnverified(int nChannels) { super.nChannels = nChannels; } @Override public void setNSlicesUnverified(int nSlices) { super.nSlices = nSlices; } @Override public void setNFramesUnverified(int nFrames) { super.nFrames = nFrames; } private void superDraw() { super.draw(); } @Override public void draw() { Runnable runnable = new Runnable() { public void run() { imageChangedUpdate(); superDraw(); } }; invokeLaterIfNotEDT(runnable); } @Override public void drawWithoutUpdate() { super.getWindow().getCanvas().setImageUpdated(); super.draw(); } } public class MMImagePlus extends ImagePlus implements IMMImagePlus { public VirtualAcquisitionDisplay display_; MMImagePlus(String title, ImageStack stack, VirtualAcquisitionDisplay disp) { super(title, stack); display_ = disp; } @Override public String getTitle() { return name_; } @Override public int getImageStackSize() { return super.nChannels * super.nSlices * super.nFrames; } @Override public int getStackSize() { return getImageStackSize(); } @Override public int getNChannelsUnverified() { return super.nChannels; } @Override public int getNSlicesUnverified() { return super.nSlices; } @Override public int getNFramesUnverified() { return super.nFrames; } @Override public void setNChannelsUnverified(int nChannels) { super.nChannels = nChannels; } @Override public void setNSlicesUnverified(int nSlices) { super.nSlices = nSlices; } @Override public void setNFramesUnverified(int nFrames) { super.nFrames = nFrames; } private void superDraw() { super.draw(); } @Override public void draw() { if (!SwingUtilities.isEventDispatchThread()) { Runnable onEDT = new Runnable() { public void run() { imageChangedUpdate(); superDraw(); } }; SwingUtilities.invokeLater(onEDT); } else { imageChangedUpdate(); super.draw(); } } @Override public void drawWithoutUpdate() { //ImageJ requires this super.getWindow().getCanvas().setImageUpdated(); super.draw(); } } public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng) { this(imageCache, eng, WindowManager.getUniqueName("Untitled")); } public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng, String name) { name_ = name; imageCache_ = imageCache; eng_ = eng; pSelector_ = createPositionScrollbar(); imageCache_.setDisplay(this); mda_ = eng != null; zStackMins_ = new HashMap<Integer, Integer>(); zStackMaxes_ = new HashMap<Integer, Integer>(); } //used for snap and live public VirtualAcquisitionDisplay(ImageCache imageCache, String name) throws MMScriptException { simple_ = true; imageCache_ = imageCache; name_ = name; System.out.println(); imageCache_.setDisplay(this); mda_ = false; } private void invokeAndWaitIfNotEDT(Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { try { SwingUtilities.invokeAndWait(runnable); } catch (InterruptedException ex) { ReportingUtils.logError(ex); } catch (InvocationTargetException ex) { System.out.println(ex.getCause()); } } } private void invokeLaterIfNotEDT(Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { SwingUtilities.invokeLater(runnable); } } private void startup(JSONObject firstImageMetadata) { mdPanel_ = MMStudioMainFrame.getInstance().getMetadataPanel(); JSONObject summaryMetadata = getSummaryMetadata(); int numSlices = 1; int numFrames = 1; int numChannels = 1; int numGrayChannels; int numPositions = 0; int width = 0; int height = 0; int numComponents = 1; try { if (firstImageMetadata != null) { width = MDUtils.getWidth(firstImageMetadata); height = MDUtils.getHeight(firstImageMetadata); } else { width = MDUtils.getWidth(summaryMetadata); height = MDUtils.getHeight(summaryMetadata); } numSlices = Math.max(summaryMetadata.getInt("Slices"), 1); numFrames = Math.max(summaryMetadata.getInt("Frames"), 1); int imageChannelIndex; try { imageChannelIndex = MDUtils.getChannelIndex(firstImageMetadata); } catch (Exception e) { imageChannelIndex = -1; } numChannels = Math.max(1 + imageChannelIndex, Math.max(summaryMetadata.getInt("Channels"), 1)); numPositions = Math.max(summaryMetadata.getInt("Positions"), 0); numComponents = Math.max(MDUtils.getNumberOfComponents(summaryMetadata), 1); } catch (Exception e) { ReportingUtils.showError(e); } numComponents_ = numComponents; numGrayChannels = numComponents_ * numChannels; channelInitiated_ = new int[numGrayChannels]; if (imageCache_.getDisplayAndComments() == null || imageCache_.getDisplayAndComments().isNull("Channels")) { imageCache_.setDisplayAndComments(getDisplaySettingsFromSummary(summaryMetadata)); } int type = 0; try { if (firstImageMetadata != null) { type = MDUtils.getSingleChannelType(firstImageMetadata); } else { type = MDUtils.getSingleChannelType(summaryMetadata); } } catch (Exception ex) { ReportingUtils.showError(ex, "Unable to determine acquisition type."); } virtualStack_ = new AcquisitionVirtualStack(width, height, type, null, imageCache_, numGrayChannels * numSlices * numFrames, this); if (summaryMetadata.has("PositionIndex")) { try { virtualStack_.setPositionIndex(MDUtils.getPositionIndex(summaryMetadata)); } catch (Exception ex) { ReportingUtils.logError(ex); } } if (simple_) { controls_ = new SimpleWindowControls(this); } else { controls_ = new HyperstackControls(this); } hyperImage_ = createHyperImage(createMMImagePlus(virtualStack_), numGrayChannels, numSlices, numFrames, virtualStack_, controls_); applyPixelSizeCalibration(hyperImage_); mdPanel_.setup(null); createWindow(); //Make sure contrast panel sets up correctly here windowToFront(); setupMetadataPanel(); cSelector_ = getSelector("c"); if (!simple_) { tSelector_ = getSelector("t"); zSelector_ = getSelector("z"); if (zSelector_ != null) { zSelector_.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { preferredSlice_ = zSelector_.getValue(); } }); } if (cSelector_ != null) { cSelector_.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { preferredChannel_ = cSelector_.getValue(); } }); } if (imageCache_.lastAcquiredFrame() > 1) { setNumFrames(1 + imageCache_.lastAcquiredFrame()); } else { setNumFrames(1); } configureAnimationControls(); //cant use these function because of an imageJ bug // setNumSlices(numSlices); setNumPositions(numPositions); } updateAndDraw(); updateWindowTitleAndStatus(); forcePainting(); } private void forcePainting() { Runnable forcePaint = new Runnable() { public void run() { if (zIcon_ != null) { zIcon_.paint(zIcon_.getGraphics()); } if (tIcon_ != null) { tIcon_.paint(tIcon_.getGraphics()); } if (cIcon_ != null) { cIcon_.paint(cIcon_.getGraphics()); } if (controls_ != null) { controls_.paint(controls_.getGraphics()); } if (pIcon_ != null && pIcon_.isValid()) { pIcon_.paint(pIcon_.getGraphics()); } } }; if (SwingUtilities.isEventDispatchThread()) { forcePaint.run(); } else { try { SwingUtilities.invokeAndWait(forcePaint); } catch (Exception ex) { ReportingUtils.logError(ex); } } } private void animateSlices(boolean animate) { if (zAnimationTimer_ == null) { zAnimationTimer_ = new Timer((int) (1000.0 / framesPerSec_), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int slice = hyperImage_.getSlice(); if (slice >= zSelector_.getMaximum() - 1) { hyperImage_.setPosition(hyperImage_.getChannel(), 1, hyperImage_.getFrame()); } else { hyperImage_.setPosition(hyperImage_.getChannel(), slice + 1, hyperImage_.getFrame()); } } }); } if (!animate) { zAnimationTimer_.stop(); refreshAnimationIcons(); return; } if (tAnimationTimer_ != null) { animateFrames(false); } zAnimationTimer_.setDelay((int) (1000.0 / framesPerSec_)); zAnimationTimer_.start(); refreshAnimationIcons(); } private void animateFrames(boolean animate) { if (tAnimationTimer_ == null) { tAnimationTimer_ = new Timer((int) (1000.0 / framesPerSec_), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int frame = hyperImage_.getFrame(); if (frame >= tSelector_.getMaximum() - 1) { hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), 1); } else { hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), frame + 1); } } }); } if (!animate) { tAnimationTimer_.stop(); refreshAnimationIcons(); return; } if (zAnimationTimer_ != null) { animateSlices(false); } tAnimationTimer_.setDelay((int) (1000.0 / framesPerSec_)); tAnimationTimer_.start(); refreshAnimationIcons(); } private void refreshAnimationIcons() { if (zIcon_ != null) { zIcon_.repaint(); } if (tIcon_ != null) { tIcon_.repaint(); } } private void configureAnimationControls() { if (zIcon_ != null) { zIcon_.addMouseListener(new MouseListener() { public void mousePressed(MouseEvent e) { animateSlices(zAnimationTimer_ == null || !zAnimationTimer_.isRunning()); } public void mouseClicked(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }); } if (tIcon_ != null) { tIcon_.addMouseListener(new MouseListener() { public void mousePressed(MouseEvent e) { animateFrames(tAnimationTimer_ == null || !tAnimationTimer_.isRunning()); } public void mouseClicked(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }); } } /** * Allows bypassing the prompt to Save * @param promptToSave boolean flag */ public void promptToSave(boolean promptToSave) { promptToSave_ = promptToSave; } /* * Method required by ImageCacheListener */ @Override public void imageReceived(final TaggedImage taggedImage) { if (eng_ != null) { updateDisplay(taggedImage, false); } } /* * Method required by ImageCacheListener */ @Override public void imagingFinished(String path) { updateDisplay(null, true); updateAndDraw(); if (eng_ != null && !eng_.abortRequested()) { updateWindowTitleAndStatus(); } } private void updateDisplay(TaggedImage taggedImage, boolean finalUpdate) { try { long t = System.currentTimeMillis(); JSONObject tags; if (taggedImage != null) { tags = taggedImage.tags; } else { tags = imageCache_.getLastImageTags(); } if (tags == null) { return; } int frame = MDUtils.getFrameIndex(tags); int ch = MDUtils.getChannelIndex(tags); int slice = MDUtils.getSliceIndex(tags); int position = MDUtils.getPositionIndex(tags); boolean show = finalUpdate || frame == 0 || (Math.abs(t - lastDisplayTime_) > 30) || (ch == getNumChannels() - 1 && lastFrameShown_ == frame && lastSliceShown_ == slice && lastPositionShown_ == position) || (slice == getNumSlices() - 1 && frame == 0 && position == 0 && ch == getNumChannels() - 1); if (show) { showImage(tags, true); lastFrameShown_ = frame; lastSliceShown_ = slice; lastPositionShown_ = position; lastDisplayTime_ = t; forceImagePaint(); } } catch (Exception e) { ReportingUtils.logError(e); } } private void forceImagePaint() { hyperImage_.getWindow().getCanvas().paint(hyperImage_.getWindow().getCanvas().getGraphics()); } public int rgbToGrayChannel(int channelIndex) { try { if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) { return channelIndex * 3; } return channelIndex; } catch (Exception ex) { ReportingUtils.logError(ex); return 0; } } public int grayToRGBChannel(int grayIndex) { try { if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) { return grayIndex / 3; } return grayIndex; } catch (Exception ex) { ReportingUtils.logError(ex); return 0; } } public static JSONObject getDisplaySettingsFromSummary(JSONObject summaryMetadata) { try { JSONObject displaySettings = new JSONObject(); JSONArray chColors = MDUtils.getJSONArrayMember(summaryMetadata, "ChColors"); JSONArray chNames = MDUtils.getJSONArrayMember(summaryMetadata, "ChNames"); JSONArray chMaxes, chMins; if ( summaryMetadata.has("ChContrastMin")) { chMins = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMin"); } else { chMins = new JSONArray(); for (int i = 0; i < chNames.length(); i++) chMins.put(0); } if ( summaryMetadata.has("ChContrastMax")) { chMaxes = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMax"); } else { int max = 65536; if (summaryMetadata.has("BitDepth")) max = (int) (Math.pow(2, summaryMetadata.getInt("BitDepth"))-1); chMaxes = new JSONArray(); for (int i = 0; i < chNames.length(); i++) chMaxes.put(max); } int numComponents = MDUtils.getNumberOfComponents(summaryMetadata); JSONArray channels = new JSONArray(); if (numComponents > 1) //RGB { int rgbChannelBitDepth = summaryMetadata.getString("PixelType").endsWith("32") ? 8 : 16; for (int k = 0; k < 3; k++) { JSONObject channelObject = new JSONObject(); channelObject.put("Color", rgb[k].getRGB()); channelObject.put("Name", rgbNames[k]); channelObject.put("Gamma", 1.0); channelObject.put("Min", 0); channelObject.put("Max", Math.pow(2, rgbChannelBitDepth) - 1); channels.put(channelObject); } } else { for (int k = 0; k < chNames.length(); ++k) { String name = (String) chNames.get(k); int color = chColors.getInt(k); int min = chMins.getInt(k); int max = chMaxes.getInt(k); JSONObject channelObject = new JSONObject(); channelObject.put("Color", color); channelObject.put("Name", name); channelObject.put("Gamma", 1.0); channelObject.put("Min", min); channelObject.put("Max", max); channels.put(channelObject); } } displaySettings.put("Channels", channels); JSONObject comments = new JSONObject(); String summary = ""; try { summary = summaryMetadata.getString("Comment"); } catch (JSONException ex) { summaryMetadata.put("Comment", ""); } comments.put("Summary", summary); displaySettings.put("Comments", comments); return displaySettings; } catch (Exception e) { ReportingUtils.showError("Error creating display settigns from summary metadata"); return null; } } /** * Sets ImageJ pixel size calibration * @param hyperImage */ private void applyPixelSizeCalibration(final ImagePlus hyperImage) { try { double pixSizeUm = getSummaryMetadata().getDouble("PixelSize_um"); if (pixSizeUm > 0) { Calibration cal = new Calibration(); cal.setUnit("um"); cal.pixelWidth = pixSizeUm; cal.pixelHeight = pixSizeUm; hyperImage.setCalibration(cal); } } catch (JSONException ex) { // no pixelsize defined. Nothing to do } } private void setNumPositions(int n) { if (simple_) { return; } pSelector_.setMinimum(0); pSelector_.setMaximum(n); ImageWindow win = hyperImage_.getWindow(); if (n > 1 && pSelector_.getParent() == null) { win.add(pSelector_, win.getComponentCount() - 1); } else if (n <= 1 && pSelector_.getParent() != null) { win.remove(pSelector_); } win.pack(); } private void setNumFrames(int n) { if (simple_) { return; } if (tSelector_ != null) { //ImageWindow win = hyperImage_.getWindow(); ((IMMImagePlus) hyperImage_).setNFramesUnverified(n); tSelector_.setMaximum(n + 1); // JavaUtils.setRestrictedFieldValue(win, StackWindow.class, "nFrames", n); } } private void setNumSlices(int n) { if (simple_) { return; } if (zSelector_ != null) { ((IMMImagePlus) hyperImage_).setNSlicesUnverified(n); zSelector_.setMaximum(n + 1); } } private void setNumChannels(int n) { if (cSelector_ != null) { ((IMMImagePlus) hyperImage_).setNChannelsUnverified(n); cSelector_.setMaximum(n); } } public ImagePlus getHyperImage() { return hyperImage_; } public int getStackSize() { if (hyperImage_ == null) { return -1; } int s = hyperImage_.getNSlices(); int c = hyperImage_.getNChannels(); int f = hyperImage_.getNFrames(); if ((s > 1 && c > 1) || (c > 1 && f > 1) || (f > 1 && s > 1)) { return s * c * f; } return Math.max(Math.max(s, c), f); } private void imageChangedWindowUpdate() { if (hyperImage_ != null && hyperImage_.isVisible()) { TaggedImage ti = virtualStack_.getTaggedImage(hyperImage_.getCurrentSlice()); if (ti != null) { controls_.newImageUpdate(ti.tags); } } } public void updateAndDraw() { if (!updating_) { updating_ = true; setupMetadataPanel(); if (hyperImage_ != null && hyperImage_.isVisible()) { hyperImage_.updateAndDraw(); } updating_ = false; } } public void updateWindowTitleAndStatus() { if (simple_) { if (hyperImage_ != null && hyperImage_.getWindow() != null) { // hyperImage_.getWindow().setTitle(name_); } return; } if (controls_ == null) { return; } String status = ""; final AcquisitionEngine eng = eng_; if (eng != null) { if (acquisitionIsRunning()) { if (!abortRequested()) { controls_.acquiringImagesUpdate(true); if (isPaused()) { status = "paused"; } else { status = "running"; } } else { controls_.acquiringImagesUpdate(false); status = "interrupted"; } } else { controls_.acquiringImagesUpdate(false); if (!status.contentEquals("interrupted")) { if (eng.isFinished()) { status = "finished"; eng_ = null; } } } status += ", "; if (eng.isFinished()) { eng_ = null; finished_ = true; } } else { if (finished_ == true) { status = "finished, "; } controls_.acquiringImagesUpdate(false); } if (isDiskCached()) { status += "on disk"; } else { status += "not yet saved"; } controls_.imagesOnDiskUpdate(imageCache_.getDiskLocation() != null); String path = isDiskCached() ? new File(imageCache_.getDiskLocation()).getName() : name_; if (hyperImage_.isVisible()) { hyperImage_.getWindow().setTitle(path + " (" + status + ")"); } } private void windowToFront() { if (hyperImage_ == null || hyperImage_.getWindow() == null) { return; } hyperImage_.getWindow().toFront(); } private void setupMetadataPanel() { if (hyperImage_ == null || hyperImage_.getWindow() == null) { return; } //call this explicitly because it isn't fired immediately mdPanel_.setup(hyperImage_.getWindow()); } /** * Displays tagged image in the multi-D viewer * Will wait for the screen update * * @param taggedImg * @throws Exception */ public void showImage(TaggedImage taggedImg) throws Exception { showImage(taggedImg, true); } /** * Displays tagged image in the multi-D viewer * Optionally waits for the display to draw the image * * * @param taggedImg * @throws Exception */ public void showImage(TaggedImage taggedImg, boolean waitForDisplay) throws InterruptedException, InvocationTargetException { showImage(taggedImg.tags, waitForDisplay); } public void showImage(JSONObject tags, boolean waitForDisplay) throws InterruptedException, InvocationTargetException { updateWindowTitleAndStatus(); if (tags == null) { return; } if (hyperImage_ == null) { startup(tags); } final boolean framesAnimated = isTAnimated(), slicesAnimated = isZAnimated(); final int animatedFrameIndex = hyperImage_.getFrame(), animatedSliceIndex = hyperImage_.getSlice(); if (framesAnimated || slicesAnimated) { animateFrames(false); animateSlices(false); } int channel = 0, frame = 0, slice = 0, position = 0, superChannel = 0; try { frame = MDUtils.getFrameIndex(tags); slice = MDUtils.getSliceIndex(tags); channel = MDUtils.getChannelIndex(tags); position = MDUtils.getPositionIndex(tags); superChannel = this.rgbToGrayChannel(MDUtils.getChannelIndex(tags)); } catch (Exception ex) { ReportingUtils.logError(ex); } //make sure pixels get properly set if (hyperImage_ != null && frame == 0) { IMMImagePlus img = (IMMImagePlus) hyperImage_; if (img.getNChannelsUnverified() == 1) { if (img.getNSlicesUnverified() == 1) { hyperImage_.getProcessor().setPixels(virtualStack_.getPixels(1)); } } else if (hyperImage_ instanceof MMCompositeImage) { //reset rebuilds each of the channel ImageProcessors with the correct pixels //from AcquisitionVirtualStack MMCompositeImage ci = ((MMCompositeImage) hyperImage_); ci.reset(); //This line is neccessary for image processor to have correct pixels in grayscale mode ci.getProcessor().setPixels(virtualStack_.getPixels(ci.getCurrentSlice())); } } else if (hyperImage_ instanceof MMCompositeImage) { MMCompositeImage ci = ((MMCompositeImage) hyperImage_); ci.reset(); } if (cSelector_ != null) { if (cSelector_.getMaximum() <= (1 + superChannel)) { this.setNumChannels(1 + superChannel); ((CompositeImage) hyperImage_).reset(); //JavaUtils.invokeRestrictedMethod(hyperImage_, CompositeImage.class, // "setupLuts", 1 + superChannel, Integer.TYPE); } } initializeContrast(channel, slice); if (!simple_) { if (tSelector_ != null) { if (tSelector_.getMaximum() <= (1 + frame)) { this.setNumFrames(1 + frame); } } if (position + 1 >= getNumPositions()) { setNumPositions(position + 1); } setPosition(position); hyperImage_.setPosition(1 + superChannel, 1 + slice, 1 + frame); } Runnable updateAndDraw = new Runnable() { public void run() { updateAndDraw(); restartAnimationAfterShowing(animatedFrameIndex, animatedSliceIndex, framesAnimated, slicesAnimated); } }; if (!SwingUtilities.isEventDispatchThread()) { if (waitForDisplay) { SwingUtilities.invokeAndWait(updateAndDraw); } else { SwingUtilities.invokeLater(updateAndDraw); } } else { updateAndDraw(); restartAnimationAfterShowing(animatedFrameIndex, animatedSliceIndex, framesAnimated, slicesAnimated); } setPreferredScrollbarPositions(); } /** * If animation was running prior to showImage, restarts it with sliders at appropriate positions */ private void restartAnimationAfterShowing(int frame, int slice, boolean framesAnimated, boolean slicesAnimated) { if (framesAnimated) { hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), frame+1); animateFrames(true); } else if (slicesAnimated) { hyperImage_.setPosition(hyperImage_.getChannel(), slice+1, hyperImage_.getFrame()); animateSlices(true); } } /* * Live/snap should load window contrast settings * MDA should autoscale on frist image * Opening dataset should load from disoplay and comments */ private void initializeContrast(final int channel, final int slice) { Runnable autoscaleOrLoadContrast = new Runnable() { public void run() { if (!newDisplay_) { return; } if (simple_) { //Snap/live if (hyperImage_ instanceof MMCompositeImage && ((MMCompositeImage) hyperImage_).getNChannelsUnverified() - 1 != channel) { return; } mdPanel_.loadSimpleWinContrastWithoutDraw(imageCache_, hyperImage_); } else if (mda_) { //Multi D acquisition IMMImagePlus immImg = ((IMMImagePlus) hyperImage_); if (immImg.getNSlicesUnverified() > 1) { //Z stacks mdPanel_.autoscaleOverStackWithoutDraw(imageCache_, hyperImage_, channel, zStackMins_, zStackMaxes_); if (channel != immImg.getNChannelsUnverified() - 1 || slice != immImg.getNSlicesUnverified() - 1) { return; //don't set new display to false until all channels autscaled } } else { //No z stacks mdPanel_.autoscaleWithoutDraw(imageCache_, hyperImage_); if (immImg.getNChannelsUnverified() - 1 != channel) { return; } } } else //Acquire button if (hyperImage_ instanceof MMCompositeImage) { if (((MMCompositeImage) hyperImage_).getNChannelsUnverified() - 1 != channel) { return; } mdPanel_.autoscaleWithoutDraw(imageCache_, hyperImage_); } else { mdPanel_.autoscaleWithoutDraw(imageCache_, hyperImage_); // else do nothing because contrast automatically loaded from cache } newDisplay_ = false; } }; if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(autoscaleOrLoadContrast); } else { autoscaleOrLoadContrast.run(); } } private void setPreferredScrollbarPositions() { if (this.acquisitionIsRunning()) { long nextImageTime = eng_.getNextWakeTime(); if (System.nanoTime() / 1000000 - nextImageTime < -1000) { //1 sec or more until next start if (preferredPositionTimer_ == null) { preferredPositionTimer_ = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { IMMImagePlus ip = ((IMMImagePlus) hyperImage_); int c = hyperImage_.getChannel(), s = hyperImage_.getSlice(), f = hyperImage_.getFrame(); hyperImage_.setPosition(preferredChannel_ == -1 ? c : preferredChannel_, preferredSlice_ == -1 ? s : preferredSlice_, f); if (pSelector_ != null && preferredPosition_ > -1) { if (eng_.getAcqOrderMode() != AcqOrderMode.POS_TIME_CHANNEL_SLICE && eng_.getAcqOrderMode() != AcqOrderMode.POS_TIME_SLICE_CHANNEL) { setPosition(preferredPosition_); } } preferredPositionTimer_.stop();; } }); } if (preferredPositionTimer_.isRunning()) { return; } preferredPositionTimer_.start(); } } } private void updatePosition(int p) { if (simple_) { return; } virtualStack_.setPositionIndex(p); if (!hyperImage_.isComposite()) { Object pixels = virtualStack_.getPixels(hyperImage_.getCurrentSlice()); hyperImage_.getProcessor().setPixels(pixels); } else { CompositeImage ci = (CompositeImage) hyperImage_; if (ci.getMode() == CompositeImage.COMPOSITE) { for (int i = 0; i < ((MMCompositeImage) ci).getNChannelsUnverified(); i++) { ci.getProcessor(i + 1).setPixels(virtualStack_.getPixels( ci.getCurrentSlice() - ci.getChannel() + i + 1)); } } ci.getProcessor().setPixels(virtualStack_.getPixels(hyperImage_.getCurrentSlice())); } //need to call this even though updateAndDraw also calls it to get autostretch to work properly imageChangedUpdate(); updateAndDraw(); } public void setPosition(int p) { if (simple_) { return; } pSelector_.setValue(p); } public void setSliceIndex(int i) { if (simple_) { return; } final int f = hyperImage_.getFrame(); final int c = hyperImage_.getChannel(); hyperImage_.setPosition(c, i + 1, f); } public int getSliceIndex() { return hyperImage_.getSlice() - 1; } boolean pause() { if (eng_ != null) { if (eng_.isPaused()) { eng_.setPause(false); } else { eng_.setPause(true); } updateWindowTitleAndStatus(); return (eng_.isPaused()); } return false; } boolean abort() { if (eng_ != null) { if (eng_.abortRequest()) { updateWindowTitleAndStatus(); return true; } } return false; } public boolean acquisitionIsRunning() { if (eng_ != null) { return eng_.isAcquisitionRunning(); } else { return false; } } public long getNextWakeTime() { return eng_.getNextWakeTime(); } public boolean abortRequested() { if (eng_ != null) { return eng_.abortRequested(); } else { return false; } } private boolean isPaused() { if (eng_ != null) { return eng_.isPaused(); } else { return false; } } boolean saveAs() { String prefix; String root; for (;;) { File f = FileDialogs.save(hyperImage_.getWindow(), "Please choose a location for the data set", MMStudioMainFrame.MM_DATA_SET); if (f == null) // Canceled. { return false; } prefix = f.getName(); root = new File(f.getParent()).getAbsolutePath(); if (f.exists()) { ReportingUtils.showMessage(prefix + " is write only! Please choose another name."); } else { break; } } TaggedImageStorageDiskDefault newFileManager = new TaggedImageStorageDiskDefault(root + "/" + prefix, true, getSummaryMetadata()); imageCache_.saveAs(newFileManager, mda_); MMStudioMainFrame.getInstance().setAcqDirectory(root); updateWindowTitleAndStatus(); return true; } final public MMImagePlus createMMImagePlus(AcquisitionVirtualStack virtualStack) { MMImagePlus img = new MMImagePlus(imageCache_.getDiskLocation(), virtualStack, this); FileInfo fi = new FileInfo(); fi.width = virtualStack.getWidth(); fi.height = virtualStack.getHeight(); fi.fileName = virtualStack.getDirectory(); fi.url = null; img.setFileInfo(fi); return img; } final public ImagePlus createHyperImage(MMImagePlus mmIP, int channels, int slices, int frames, final AcquisitionVirtualStack virtualStack, DisplayControls hc) { final ImagePlus hyperImage; mmIP.setNChannelsUnverified(channels); mmIP.setNFramesUnverified(frames); mmIP.setNSlicesUnverified(slices); if (channels > 1) { hyperImage = new MMCompositeImage(mmIP, CompositeImage.COMPOSITE, this); hyperImage.setOpenAsHyperStack(true); } else { hyperImage = mmIP; mmIP.setOpenAsHyperStack(true); } return hyperImage; } public void liveModeEnabled(boolean enabled) { if (simple_) { controls_.acquiringImagesUpdate(enabled); } } private void createWindow() { final DisplayWindow win = new DisplayWindow(hyperImage_); win.getCanvas().addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent me) { } //used to store preferred zoom public void mousePressed(MouseEvent me) { int id = Toolbar.getToolId(); int currentLength = (win.getSize().width + win.getSize().height) / 2; if (id == 11) {//zoom tool selected if (me.getButton() == MouseEvent.BUTTON1) { //Zoom in prefs_.putInt(PREF_WIN_LENGTH, Math.max(currentLength, 512)); } else if (me.getButton() == MouseEvent.BUTTON3) { //Zoom out prefs_.putInt(PREF_WIN_LENGTH, Math.max(currentLength, 512)); } } } //updates the histogram after an ROI is drawn public void mouseReleased(MouseEvent me) { mdPanel_.refresh(); } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } }); win.setBackground(MMStudioMainFrame.getInstance().getBackgroundColor()); MMStudioMainFrame.getInstance().addMMBackgroundListener(win); win.add(controls_); win.pack(); //Set magnification zoomToPreferredSize(win); if (simple_) { win.setLocation(prefs_.getInt(SIMPLE_WIN_X, 0), prefs_.getInt(SIMPLE_WIN_Y, 0)); } } private void zoomToPreferredSize(DisplayWindow win) { int prefLength = prefs_.getInt(PREF_WIN_LENGTH, 512); int winLength = (int) Math.sqrt(win.getSize().width * win.getSize().height); double percentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength)); ImageCanvas canvas = win.getCanvas(); if (winLength < prefLength) { while (winLength < prefLength) { percentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength)); canvas.zoomIn(canvas.getSize().width / 2, canvas.getSize().height / 2); int newWinLength = (int) Math.sqrt(win.getSize().width * win.getSize().height); if (newWinLength == winLength) break; winLength = newWinLength; } double newPercentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength)); if (newPercentDiff > percentDiff) { canvas.zoomOut(canvas.getSize().width / 2, canvas.getSize().height / 2); } } else if (winLength > prefLength) { while (winLength > prefLength) { percentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength)); canvas.zoomOut(canvas.getSize().width / 2, canvas.getSize().height / 2); int newWinLength = (int) Math.sqrt(win.getSize().width * win.getSize().height); if (newWinLength == winLength) break; winLength = newWinLength; } double newPercentDiff = Math.abs(((double) (winLength - prefLength))/((double) prefLength)); if (newPercentDiff > percentDiff) { canvas.zoomIn(canvas.getSize().width / 2, canvas.getSize().height / 2); } } Rectangle rect = canvas.getSrcRect(); if (rect != null) { while (rect.width < canvas.getImage().getWidth() || rect.height < canvas.getImage().getHeight()) { if (rect.width > 0.9 * canvas.getImage().getWidth() && rect.height > 0.9 * canvas.getImage().getHeight()) { canvas.zoomOut(canvas.getSize().width / 2, canvas.getSize().height / 2); canvas.zoomIn(canvas.getSize().width / 2, canvas.getSize().height / 2); break; } else { canvas.zoomOut(canvas.getSize().width / 2, canvas.getSize().height / 2); } rect = canvas.getSrcRect(); if (rect == null) { break; } } } } private ScrollbarWithLabel getSelector(String label) { // label should be "t", "z", or "c" ScrollbarWithLabel selector = null; ImageWindow win = hyperImage_.getWindow(); int slices = ((IMMImagePlus) hyperImage_).getNSlicesUnverified(); int frames = ((IMMImagePlus) hyperImage_).getNFramesUnverified(); int channels = ((IMMImagePlus) hyperImage_).getNChannelsUnverified(); if (win instanceof StackWindow) { try { //ImageJ bug workaround if (frames > 1 && slices == 1 && channels == 1 && label.equals("t")) { selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, "zSelector"); } else { selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, label + "Selector"); } } catch (NoSuchFieldException ex) { selector = null; ReportingUtils.logError(ex); } } //replace default icon with custom one if (selector != null) { try { Component icon = (Component) JavaUtils.getRestrictedFieldValue( selector, ScrollbarWithLabel.class, "icon"); selector.remove(icon); } catch (NoSuchFieldException ex) { ReportingUtils.logError(ex); } ScrollbarIcon newIcon = new ScrollbarIcon(label.charAt(0), this); if (label.equals("z")) { zIcon_ = newIcon; } else if (label.equals("t")) { tIcon_ = newIcon; } else if (label.equals("c")) { cIcon_ = newIcon; } selector.add(newIcon, BorderLayout.WEST); selector.invalidate(); selector.validate(); } return selector; } private ScrollbarWithLabel createPositionScrollbar() { final ScrollbarWithLabel pSelector = new ScrollbarWithLabel(null, 1, 1, 1, 2, 'p') { @Override public void setValue(int v) { if (this.getValue() != v) { super.setValue(v); updatePosition(v); } } }; // prevents scroll bar from blinking on Windows: pSelector.setFocusable(false); pSelector.setUnitIncrement(1); pSelector.setBlockIncrement(1); pSelector.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { updatePosition(pSelector.getValue()); preferredPosition_ = pSelector_.getValue(); } }); if (pSelector != null) { try { Component icon = (Component) JavaUtils.getRestrictedFieldValue( pSelector, ScrollbarWithLabel.class, "icon"); pSelector.remove(icon); } catch (NoSuchFieldException ex) { ReportingUtils.logError(ex); } pIcon_ = new ScrollbarIcon('p', this); pSelector.add(pIcon_, BorderLayout.WEST); pSelector.invalidate(); pSelector.validate(); } return pSelector; } public JSONObject getCurrentMetadata() { try { if (hyperImage_ != null) { TaggedImage image = virtualStack_.getTaggedImage(hyperImage_.getCurrentSlice()); if (image != null) { return image.tags; } else { return null; } } else { return null; } } catch (NullPointerException ex) { return null; } } public int getCurrentPosition() { return virtualStack_.getPositionIndex(); } public int getNumSlices() { if (simple_) { return 1; } return ((IMMImagePlus) hyperImage_).getNSlicesUnverified(); } public int getNumFrames() { if (simple_) { return 1; } return ((IMMImagePlus) hyperImage_).getNFramesUnverified(); } public int getNumPositions() { if (simple_) { return 1; } return pSelector_.getMaximum(); } public ImagePlus getImagePlus() { return hyperImage_; } public ImageCache getImageCache() { return imageCache_; } public ImagePlus getImagePlus(int position) { ImagePlus iP = new ImagePlus(); iP.setStack(virtualStack_); iP.setDimensions(numComponents_ * getNumChannels(), getNumSlices(), getNumFrames()); iP.setFileInfo(hyperImage_.getFileInfo()); return iP; } public void setComment(String comment) throws MMScriptException { try { getSummaryMetadata().put("Comment", comment); } catch (Exception ex) { ReportingUtils.logError(ex); } } public final JSONObject getSummaryMetadata() { return imageCache_.getSummaryMetadata(); } public void close() { if (hyperImage_ != null) { //call this so when one window closes and is replaced by another //the md panel gets rid of the first before doing stuff with //the second if (WindowManager.getCurrentImage() == hyperImage_) { mdPanel_.setup(null); } hyperImage_.getWindow().windowClosing(null); hyperImage_.close(); } } public synchronized boolean windowClosed() { ImageWindow win = hyperImage_.getWindow(); return (win == null || win.isClosed()); } public void showFolder() { if (isDiskCached()) { try { File location = new File(imageCache_.getDiskLocation()); if (JavaUtils.isWindows()) { Runtime.getRuntime().exec("Explorer /n,/select," + location.getAbsolutePath()); } else if (JavaUtils.isMac()) { if (!location.isDirectory()) { location = location.getParentFile(); } Runtime.getRuntime().exec("open " + location.getAbsolutePath()); } } catch (IOException ex) { ReportingUtils.logError(ex); } } } public void setPlaybackFPS(double fps) { framesPerSec_ = fps; if (zAnimationTimer_ != null && zAnimationTimer_.isRunning()) { animateSlices(false); animateSlices(true); } else if (tAnimationTimer_ != null && tAnimationTimer_.isRunning()) { animateFrames(false); animateFrames(true); } } public double getPlaybackFPS() { return framesPerSec_; } public boolean isZAnimated() { if (zAnimationTimer_ != null && zAnimationTimer_.isRunning()) { return true; } return false; } public boolean isTAnimated() { if (tAnimationTimer_ != null && tAnimationTimer_.isRunning()) { return true; } return false; } public boolean isAnimated() { return isTAnimated() || isZAnimated(); } public String getSummaryComment() { return imageCache_.getComment(); } public void setSummaryComment(String comment) { imageCache_.setComment(comment); } void setImageComment(String comment) { imageCache_.setImageComment(comment, getCurrentMetadata()); } String getImageComment() { try { return imageCache_.getImageComment(getCurrentMetadata()); } catch (NullPointerException ex) { return ""; } } public boolean isDiskCached() { ImageCache imageCache = imageCache_; if (imageCache == null) { return false; } else { return imageCache.getDiskLocation() != null; } } public void show() { if (hyperImage_ == null) { startup(null); } hyperImage_.show(); hyperImage_.getWindow().toFront(); } public int getNumChannels() { return ((IMMImagePlus) hyperImage_).getNChannelsUnverified(); } public int getNumGrayChannels() { return getNumChannels(); } public void setWindowTitle(String name) { name_ = name; updateWindowTitleAndStatus(); } public boolean isSimpleDisplay() { return simple_; } public void displayStatusLine(String status) { controls_.setStatusLabel(status); } public void setChannelContrast(int channelIndex, int min, int max, double gamma) { mdPanel_.setChannelContrast(channelIndex, min, max, gamma); } private void imageChangedUpdate() { mdPanel_.imageChangedUpdate(hyperImage_, imageCache_); imageChangedWindowUpdate(); //used to update status line } public void refreshContrastPanel() { mdPanel_.refresh(); } public void drawWithoutUpdate() { if (hyperImage_ != null) { ((IMMImagePlus) hyperImage_).drawWithoutUpdate(); } } public class DisplayWindow extends StackWindow { private boolean windowClosingDone_ = false; private boolean closed_ = false; public DisplayWindow(ImagePlus ip) { super(ip); } @Override public boolean close() { windowClosing(null); return closed_; } @Override public void windowClosing(WindowEvent e) { if (windowClosingDone_) { return; } if (eng_ != null && eng_.isAcquisitionRunning()) { if (!abort()) { return; } } if (imageCache_.getDiskLocation() == null && promptToSave_) { int result = JOptionPane.showConfirmDialog(this, "This data set has not yet been saved.\n" + "Do you want to save it?", "Micro-Manager", JOptionPane.YES_NO_CANCEL_OPTION); if (result == JOptionPane.YES_OPTION) { if (!saveAs()) { return; } } else if (result == JOptionPane.CANCEL_OPTION) { return; } } //for some reason window focus listener doesn't always fire, so call //explicitly here mdPanel_.setup(null); if (simple_ && hyperImage_ != null && hyperImage_.getWindow() != null && hyperImage_.getWindow().getLocation() != null) { Point loc = hyperImage_.getWindow().getLocation(); prefs_.putInt(SIMPLE_WIN_X, loc.x); prefs_.putInt(SIMPLE_WIN_Y, loc.y); mdPanel_.saveContrastSettings(imageCache_); } if (imageCache_ != null) { imageCache_.close(); } if (!closed_) { try { super.close(); } catch (NullPointerException ex) { ReportingUtils.logError("Null pointer error in ImageJ code while closing window"); } } super.windowClosing(e); MMStudioMainFrame.getInstance().removeMMBackgroundListener(this); windowClosingDone_ = true; closed_ = true; } @Override public void windowClosed(WindowEvent E) { this.windowClosing(E); super.windowClosed(E); } @Override public void windowActivated(WindowEvent e) { if (!isClosed()) { super.windowActivated(e); } } @Override public void setAnimate(boolean b) { if (((IMMImagePlus) hyperImage_).getNFramesUnverified() > 1) { animateFrames(b); } else { animateSlices(b); } } @Override public boolean getAnimate() { return isAnimated(); } }; }
Correct zoom level always displayed on window title git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@8905 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
mmstudio/src/org/micromanager/acquisition/VirtualAcquisitionDisplay.java
Correct zoom level always displayed on window title
<ide><path>mstudio/src/org/micromanager/acquisition/VirtualAcquisitionDisplay.java <ide> <ide> public void updateWindowTitleAndStatus() { <ide> if (simple_) { <del> if (hyperImage_ != null && hyperImage_.getWindow() != null) { <del>// hyperImage_.getWindow().setTitle(name_); <del> } <add> int mag = (int) (100 * hyperImage_.getCanvas().getMagnification()); <add> String title = hyperImage_.getTitle() + " ("+mag+"%)"; <add> hyperImage_.getWindow().setTitle(title); <ide> return; <ide> } <ide> if (controls_ == null) { <ide> ? new File(imageCache_.getDiskLocation()).getName() : name_; <ide> <ide> if (hyperImage_.isVisible()) { <del> hyperImage_.getWindow().setTitle(path + " (" + status + ")"); <add> int mag = (int) (100 * hyperImage_.getCanvas().getMagnification()); <add> hyperImage_.getWindow().setTitle(path + " (" + status + ") (" + mag + "%)" ); <ide> } <ide> <ide> } <ide> prefs_.putInt(PREF_WIN_LENGTH, Math.max(currentLength, 512)); <ide> } <ide> } <add> updateWindowTitleAndStatus(); <ide> } <ide> <ide> //updates the histogram after an ROI is drawn
Java
mit
0a8f8a1d22c0ac518eb476e694c4bddd90994e45
0
conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5
package com.conveyal.r5.analyst.scenario; import com.conveyal.gtfs.model.Route; import com.conveyal.gtfs.model.Service; import com.conveyal.r5.streets.StreetRouter; import com.conveyal.r5.streets.VertexStore; import com.conveyal.r5.transit.TransportNetwork; import com.conveyal.r5.transit.TripPattern; import com.conveyal.r5.transit.TripSchedule; import gnu.trove.list.TIntList; import gnu.trove.map.TIntIntMap; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static com.conveyal.r5.analyst.scenario.FakeGraph.buildNetwork; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Test adding trips. */ public class AddTripsTest { public TransportNetwork network; public long checksum; @Before public void setUp () { network = buildNetwork(FakeGraph.TransitNetwork.SINGLE_LINE); checksum = network.checksum(); } /** simple test of adding a unidirectional trip with one frequency entry and no added stops */ @Test public void testAddUnidirectionalTrip () { assertEquals(1, network.transitLayer.tripPatterns.size()); AddTrips at = new AddTrips(); at.bidirectional = false; at.stops = Arrays.asList( new StopSpec("SINGLE_LINE:s1"), new StopSpec("SINGLE_LINE:s2"), new StopSpec("SINGLE_LINE:s3") ); at.mode = Route.BUS; AddTrips.PatternTimetable entry = new AddTrips.PatternTimetable(); entry.frequency = true; entry.headwaySecs = 900; entry.monday = entry.tuesday = entry.wednesday = entry.thursday = entry.friday = true; entry.saturday = entry.sunday = false; entry.hopTimes = new int[] { 120, 140 }; entry.dwellTimes = new int[] { 0, 30, 0 }; entry.startTime = 7 * 3600; entry.endTime = 10 * 3600; at.frequencies = Arrays.asList(entry); Scenario scenario = new Scenario(); scenario.modifications = Arrays.asList(at); TransportNetwork mod = scenario.applyToTransportNetwork(network); assertEquals(2, mod.transitLayer.tripPatterns.size()); // find the added trip pattern TripPattern pattern = mod.transitLayer.tripPatterns.stream() .filter(pat -> pat.tripSchedules.get(0).headwaySeconds != null) .findFirst() .orElse(null); // was it added? assertNotNull(pattern); // make sure the stops are in the right order assertEquals(3, pattern.stops.length); assertEquals("SINGLE_LINE:s1", mod.transitLayer.stopIdForIndex.get(pattern.stops[0])); assertEquals("SINGLE_LINE:s2", mod.transitLayer.stopIdForIndex.get(pattern.stops[1])); assertEquals("SINGLE_LINE:s3", mod.transitLayer.stopIdForIndex.get(pattern.stops[2])); // check the timetable assertEquals(1, pattern.tripSchedules.size()); TripSchedule ts = pattern.tripSchedules.get(0); assertEquals(3, ts.departures.length); assertEquals(3, ts.arrivals.length); assertEquals(0, ts.arrivals[0]); assertEquals(0, ts.departures[0]); assertEquals(120, ts.arrivals[1]); assertEquals(150, ts.departures[1]); assertEquals(290, ts.arrivals[2]); assertEquals(290, ts.departures[2]); // check the frequency assertArrayEquals(new int[] { entry.headwaySecs }, ts.headwaySeconds); assertArrayEquals(new int[] { entry.startTime }, ts.startTimes); assertArrayEquals(new int[] { entry.endTime }, ts.endTimes); // check the calendar Service service0 = mod.transitLayer.services.get(ts.serviceCode); assertEquals(entry.monday, service0.calendar.monday == 1); assertEquals(entry.tuesday, service0.calendar.tuesday == 1); assertEquals(entry.wednesday, service0.calendar.wednesday == 1); assertEquals(entry.thursday, service0.calendar.thursday == 1); assertEquals(entry.friday, service0.calendar.friday == 1); assertEquals(entry.saturday, service0.calendar.saturday == 1); assertEquals(entry.sunday, service0.calendar.sunday == 1); assertEquals(checksum, network.checksum()); } /** simple test of adding a bidirectional trip with one frequency entry and no added stops */ @Test public void testAddBidirectionalTrip () { assertEquals(1, network.transitLayer.tripPatterns.size()); AddTrips at = new AddTrips(); at.bidirectional = true; at.stops = Arrays.asList( new StopSpec("SINGLE_LINE:s1"), new StopSpec("SINGLE_LINE:s2"), new StopSpec("SINGLE_LINE:s3") ); at.mode = Route.BUS; AddTrips.PatternTimetable entry = new AddTrips.PatternTimetable(); entry.frequency = true; entry.headwaySecs = 900; entry.monday = entry.tuesday = entry.wednesday = entry.thursday = entry.friday = true; entry.saturday = entry.sunday = false; entry.hopTimes = new int[] { 120, 140 }; entry.dwellTimes = new int[] { 0, 30, 0 }; entry.startTime = 7 * 3600; entry.endTime = 10 * 3600; at.frequencies = Arrays.asList(entry); Scenario scenario = new Scenario(); scenario.modifications = Arrays.asList(at); TransportNetwork mod = scenario.applyToTransportNetwork(network); assertEquals(3, mod.transitLayer.tripPatterns.size()); // find the added trip patterns List<TripPattern> patterns = mod.transitLayer.tripPatterns.stream() .filter(pat -> pat.tripSchedules.get(0).headwaySeconds != null) .collect(Collectors.toList()); assertEquals(2, patterns.size()); TripPattern pattern, backPattern; // sort out forward and back patterns if ("SINGLE_LINE:s1".equals(mod.transitLayer.stopIdForIndex.get(patterns.get(0).stops[0]))) { pattern = patterns.get(0); backPattern = patterns.get(1); } else { pattern = patterns.get(1); backPattern = patterns.get(0); } // make sure the stops are in the right order assertEquals(3, pattern.stops.length); assertEquals("SINGLE_LINE:s1", mod.transitLayer.stopIdForIndex.get(pattern.stops[0])); assertEquals("SINGLE_LINE:s2", mod.transitLayer.stopIdForIndex.get(pattern.stops[1])); assertEquals("SINGLE_LINE:s3", mod.transitLayer.stopIdForIndex.get(pattern.stops[2])); // check the timetable assertEquals(1, pattern.tripSchedules.size()); TripSchedule ts = pattern.tripSchedules.get(0); assertEquals(3, ts.departures.length); assertEquals(3, ts.arrivals.length); assertEquals(0, ts.arrivals[0]); assertEquals(0, ts.departures[0]); assertEquals(120, ts.arrivals[1]); assertEquals(150, ts.departures[1]); assertEquals(290, ts.arrivals[2]); assertEquals(290, ts.departures[2]); // check the frequency assertArrayEquals(new int[] { entry.headwaySecs }, ts.headwaySeconds); assertArrayEquals(new int[] { entry.startTime }, ts.startTimes); assertArrayEquals(new int[] { entry.endTime }, ts.endTimes); // check the calendar Service service0 = mod.transitLayer.services.get(ts.serviceCode); assertEquals(entry.monday, service0.calendar.monday == 1); assertEquals(entry.tuesday, service0.calendar.tuesday == 1); assertEquals(entry.wednesday, service0.calendar.wednesday == 1); assertEquals(entry.thursday, service0.calendar.thursday == 1); assertEquals(entry.friday, service0.calendar.friday == 1); assertEquals(entry.saturday, service0.calendar.saturday == 1); assertEquals(entry.sunday, service0.calendar.sunday == 1); // now do it all backwards // make sure the stops are in the right order assertEquals(3, backPattern.stops.length); assertEquals("SINGLE_LINE:s3", mod.transitLayer.stopIdForIndex.get(backPattern.stops[0])); assertEquals("SINGLE_LINE:s2", mod.transitLayer.stopIdForIndex.get(backPattern.stops[1])); assertEquals("SINGLE_LINE:s1", mod.transitLayer.stopIdForIndex.get(backPattern.stops[2])); // check the timetable assertEquals(1, backPattern.tripSchedules.size()); ts = backPattern.tripSchedules.get(0); assertEquals(3, ts.departures.length); assertEquals(3, ts.arrivals.length); assertEquals(0, ts.arrivals[0]); assertEquals(0, ts.departures[0]); assertEquals(140, ts.arrivals[1]); assertEquals(170, ts.departures[1]); assertEquals(290, ts.arrivals[2]); assertEquals(290, ts.departures[2]); // check the frequency assertArrayEquals(new int[] { entry.headwaySecs }, ts.headwaySeconds); assertArrayEquals(new int[] { entry.startTime }, ts.startTimes); assertArrayEquals(new int[] { entry.endTime }, ts.endTimes); // check the calendar service0 = mod.transitLayer.services.get(ts.serviceCode); assertEquals(entry.monday, service0.calendar.monday == 1); assertEquals(entry.tuesday, service0.calendar.tuesday == 1); assertEquals(entry.wednesday, service0.calendar.wednesday == 1); assertEquals(entry.thursday, service0.calendar.thursday == 1); assertEquals(entry.friday, service0.calendar.friday == 1); assertEquals(entry.saturday, service0.calendar.saturday == 1); assertEquals(entry.sunday, service0.calendar.sunday == 1); assertEquals(checksum, network.checksum()); } /** * Simple test of adding a unidirectional trip with one frequency entry and a newly created stop. */ @Test public void testAddUnidirectionalTripWithAddedStops () { assertEquals(1, network.transitLayer.tripPatterns.size()); AddTrips at = new AddTrips(); at.bidirectional = false; at.stops = Arrays.asList( new StopSpec("SINGLE_LINE:s1"), new StopSpec(-83.001, 40.012), new StopSpec("SINGLE_LINE:s3") ); at.mode = Route.BUS; AddTrips.PatternTimetable entry = new AddTrips.PatternTimetable(); entry.frequency = true; entry.headwaySecs = 900; entry.monday = entry.tuesday = entry.wednesday = entry.thursday = entry.friday = true; entry.saturday = entry.sunday = false; entry.hopTimes = new int[] { 120, 140 }; entry.dwellTimes = new int[] { 0, 30, 0 }; entry.startTime = 7 * 3600; entry.endTime = 10 * 3600; at.frequencies = Arrays.asList(entry); Scenario scenario = new Scenario(); scenario.modifications = Arrays.asList(at); TransportNetwork mod = scenario.applyToTransportNetwork(network); assertEquals(2, mod.transitLayer.tripPatterns.size()); // find the added trip pattern TripPattern pattern = mod.transitLayer.tripPatterns.stream() .filter(pat -> pat.tripSchedules.get(0).headwaySeconds != null) .findFirst() .orElse(null); // was it added? assertNotNull(pattern); // make sure the stops are in the right order assertEquals(3, pattern.stops.length); assertEquals("SINGLE_LINE:s1", mod.transitLayer.stopIdForIndex.get(pattern.stops[0])); assertEquals("SINGLE_LINE:s3", mod.transitLayer.stopIdForIndex.get(pattern.stops[2])); int createdVertex = mod.transitLayer.streetVertexForStop.get(pattern.stops[1]); VertexStore.Vertex v = mod.streetLayer.vertexStore.getCursor(createdVertex); // make sure the stop is in the right place assertEquals(40.012, v.getLat(), 1e-6); assertEquals(-83.001, v.getLon(), 1e-6); // make sure it's linked to the street network StreetRouter r = new StreetRouter(mod.streetLayer); r.setOrigin(createdVertex); r.distanceLimitMeters = 500; r.route(); assertTrue(r.getReachedVertices().size() > 5); // make sure it has a stop tree TIntIntMap stopTree = mod.transitLayer.stopTrees.get(pattern.stops[1]); assertNotNull(stopTree); assertFalse(stopTree.isEmpty()); // make sure it has transfers TIntList transfers = mod.transitLayer.transfersForStop.get(pattern.stops[1]); assertNotNull(transfers); // make sure that s2 is a target of a transfer boolean s2found = false; for (int i = 0; i < transfers.size(); i += 2) { if ("SINGLE_LINE:s2".equals(mod.transitLayer.stopIdForIndex.get(transfers.get(i)))) { s2found = true; break; } } assertTrue(s2found); // check the timetable assertEquals(1, pattern.tripSchedules.size()); TripSchedule ts = pattern.tripSchedules.get(0); assertEquals(3, ts.departures.length); assertEquals(3, ts.arrivals.length); assertEquals(0, ts.arrivals[0]); assertEquals(0, ts.departures[0]); assertEquals(120, ts.arrivals[1]); assertEquals(150, ts.departures[1]); assertEquals(290, ts.arrivals[2]); assertEquals(290, ts.departures[2]); // check the frequency assertArrayEquals(new int[] { entry.headwaySecs }, ts.headwaySeconds); assertArrayEquals(new int[] { entry.startTime }, ts.startTimes); assertArrayEquals(new int[] { entry.endTime }, ts.endTimes); // check the calendar Service service0 = mod.transitLayer.services.get(ts.serviceCode); assertEquals(entry.monday, service0.calendar.monday == 1); assertEquals(entry.tuesday, service0.calendar.tuesday == 1); assertEquals(entry.wednesday, service0.calendar.wednesday == 1); assertEquals(entry.thursday, service0.calendar.thursday == 1); assertEquals(entry.friday, service0.calendar.friday == 1); assertEquals(entry.saturday, service0.calendar.saturday == 1); assertEquals(entry.sunday, service0.calendar.sunday == 1); assertEquals(checksum, network.checksum()); } @After public void tearDown () { this.network = null; } }
src/test/java/com/conveyal/r5/analyst/scenario/AddTripsTest.java
package com.conveyal.r5.analyst.scenario; import com.conveyal.gtfs.model.Route; import com.conveyal.gtfs.model.Service; import com.conveyal.r5.streets.StreetRouter; import com.conveyal.r5.streets.VertexStore; import com.conveyal.r5.transit.TransportNetwork; import com.conveyal.r5.transit.TripPattern; import com.conveyal.r5.transit.TripSchedule; import gnu.trove.list.TIntList; import gnu.trove.map.TIntIntMap; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static com.conveyal.r5.analyst.scenario.FakeGraph.buildNetwork; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Test adding trips. */ public class AddTripsTest { public TransportNetwork network; public long checksum; @Before public void setUp () { network = buildNetwork(FakeGraph.TransitNetwork.SINGLE_LINE); checksum = network.checksum(); } /** simple test of adding a unidirectional trip with one frequency entry and no added stops */ @Test public void testAddUnidirectionalTrip () { assertEquals(1, network.transitLayer.tripPatterns.size()); AddTrips at = new AddTrips(); at.bidirectional = false; at.stops = Arrays.asList( new StopSpec("SINGLE_LINE:s1"), new StopSpec("SINGLE_LINE:s2"), new StopSpec("SINGLE_LINE:s3") ); at.mode = Route.BUS; AddTrips.PatternTimetable entry = new AddTrips.PatternTimetable(); entry.frequency = true; entry.headwaySecs = 900; entry.monday = entry.tuesday = entry.wednesday = entry.thursday = entry.friday = true; entry.saturday = entry.sunday = false; entry.hopTimes = new int[] { 120, 140 }; entry.dwellTimes = new int[] { 0, 30, 0 }; entry.startTime = 7 * 3600; entry.endTime = 10 * 3600; at.frequencies = Arrays.asList(entry); Scenario scenario = new Scenario(); scenario.modifications = Arrays.asList(at); TransportNetwork mod = scenario.applyToTransportNetwork(network); assertEquals(2, mod.transitLayer.tripPatterns.size()); // find the added trip pattern TripPattern pattern = mod.transitLayer.tripPatterns.stream() .filter(pat -> pat.tripSchedules.get(0).headwaySeconds != null) .findFirst() .orElse(null); // was it added? assertNotNull(pattern); // make sure the stops are in the right order assertEquals(3, pattern.stops.length); assertEquals("SINGLE_LINE:s1", mod.transitLayer.stopIdForIndex.get(pattern.stops[0])); assertEquals("SINGLE_LINE:s2", mod.transitLayer.stopIdForIndex.get(pattern.stops[1])); assertEquals("SINGLE_LINE:s3", mod.transitLayer.stopIdForIndex.get(pattern.stops[2])); // check the timetable assertEquals(1, pattern.tripSchedules.size()); TripSchedule ts = pattern.tripSchedules.get(0); assertEquals(3, ts.departures.length); assertEquals(3, ts.arrivals.length); assertEquals(0, ts.arrivals[0]); assertEquals(0, ts.departures[0]); assertEquals(120, ts.arrivals[1]); assertEquals(150, ts.departures[1]); assertEquals(290, ts.arrivals[2]); assertEquals(290, ts.departures[2]); // check the frequency assertArrayEquals(new int[] { entry.headwaySecs }, ts.headwaySeconds); assertArrayEquals(new int[] { entry.startTime }, ts.startTimes); assertArrayEquals(new int[] { entry.endTime }, ts.endTimes); // check the calendar Service service0 = mod.transitLayer.services.get(ts.serviceCode); assertEquals(entry.monday, service0.calendar.monday == 1); assertEquals(entry.tuesday, service0.calendar.tuesday == 1); assertEquals(entry.wednesday, service0.calendar.wednesday == 1); assertEquals(entry.thursday, service0.calendar.thursday == 1); assertEquals(entry.friday, service0.calendar.friday == 1); assertEquals(entry.saturday, service0.calendar.saturday == 1); assertEquals(entry.sunday, service0.calendar.sunday == 1); assertEquals(checksum, network.checksum()); } /** simple test of adding a bidirectional trip with one frequency entry and no added stops */ @Test public void testAddBidirectionalTrip () { assertEquals(1, network.transitLayer.tripPatterns.size()); AddTrips at = new AddTrips(); at.bidirectional = true; at.stops = Arrays.asList( new StopSpec("SINGLE_LINE:s1"), new StopSpec("SINGLE_LINE:s2"), new StopSpec("SINGLE_LINE:s3") ); at.mode = Route.BUS; AddTrips.PatternTimetable entry = new AddTrips.PatternTimetable(); entry.frequency = true; entry.headwaySecs = 900; entry.monday = entry.tuesday = entry.wednesday = entry.thursday = entry.friday = true; entry.saturday = entry.sunday = false; entry.hopTimes = new int[] { 120, 140 }; entry.dwellTimes = new int[] { 0, 30, 0 }; entry.startTime = 7 * 3600; entry.endTime = 10 * 3600; at.frequencies = Arrays.asList(entry); Scenario scenario = new Scenario(); scenario.modifications = Arrays.asList(at); TransportNetwork mod = scenario.applyToTransportNetwork(network); assertEquals(3, mod.transitLayer.tripPatterns.size()); // find the added trip patterns List<TripPattern> patterns = mod.transitLayer.tripPatterns.stream() .filter(pat -> pat.tripSchedules.get(0).headwaySeconds != null) .collect(Collectors.toList()); assertEquals(2, patterns.size()); TripPattern pattern, backPattern; // sort out forward and back patterns if ("SINGLE_LINE:s1".equals(mod.transitLayer.stopIdForIndex.get(patterns.get(0).stops[0]))) { pattern = patterns.get(0); backPattern = patterns.get(1); } else { pattern = patterns.get(1); backPattern = patterns.get(0); } // make sure the stops are in the right order assertEquals(3, pattern.stops.length); assertEquals("SINGLE_LINE:s1", mod.transitLayer.stopIdForIndex.get(pattern.stops[0])); assertEquals("SINGLE_LINE:s2", mod.transitLayer.stopIdForIndex.get(pattern.stops[1])); assertEquals("SINGLE_LINE:s3", mod.transitLayer.stopIdForIndex.get(pattern.stops[2])); // check the timetable assertEquals(1, pattern.tripSchedules.size()); TripSchedule ts = pattern.tripSchedules.get(0); assertEquals(3, ts.departures.length); assertEquals(3, ts.arrivals.length); assertEquals(0, ts.arrivals[0]); assertEquals(0, ts.departures[0]); assertEquals(120, ts.arrivals[1]); assertEquals(150, ts.departures[1]); assertEquals(290, ts.arrivals[2]); assertEquals(290, ts.departures[2]); // check the frequency assertArrayEquals(new int[] { entry.headwaySecs }, ts.headwaySeconds); assertArrayEquals(new int[] { entry.startTime }, ts.startTimes); assertArrayEquals(new int[] { entry.endTime }, ts.endTimes); // check the calendar Service service0 = mod.transitLayer.services.get(ts.serviceCode); assertEquals(entry.monday, service0.calendar.monday == 1); assertEquals(entry.tuesday, service0.calendar.tuesday == 1); assertEquals(entry.wednesday, service0.calendar.wednesday == 1); assertEquals(entry.thursday, service0.calendar.thursday == 1); assertEquals(entry.friday, service0.calendar.friday == 1); assertEquals(entry.saturday, service0.calendar.saturday == 1); assertEquals(entry.sunday, service0.calendar.sunday == 1); // now do it all backwards // make sure the stops are in the right order assertEquals(3, backPattern.stops.length); assertEquals("SINGLE_LINE:s3", mod.transitLayer.stopIdForIndex.get(backPattern.stops[0])); assertEquals("SINGLE_LINE:s2", mod.transitLayer.stopIdForIndex.get(backPattern.stops[1])); assertEquals("SINGLE_LINE:s1", mod.transitLayer.stopIdForIndex.get(backPattern.stops[2])); // check the timetable assertEquals(1, backPattern.tripSchedules.size()); ts = backPattern.tripSchedules.get(0); assertEquals(3, ts.departures.length); assertEquals(3, ts.arrivals.length); assertEquals(0, ts.arrivals[0]); assertEquals(0, ts.departures[0]); assertEquals(140, ts.arrivals[1]); assertEquals(170, ts.departures[1]); assertEquals(290, ts.arrivals[2]); assertEquals(290, ts.departures[2]); // check the frequency assertArrayEquals(new int[] { entry.headwaySecs }, ts.headwaySeconds); assertArrayEquals(new int[] { entry.startTime }, ts.startTimes); assertArrayEquals(new int[] { entry.endTime }, ts.endTimes); // check the calendar service0 = mod.transitLayer.services.get(ts.serviceCode); assertEquals(entry.monday, service0.calendar.monday == 1); assertEquals(entry.tuesday, service0.calendar.tuesday == 1); assertEquals(entry.wednesday, service0.calendar.wednesday == 1); assertEquals(entry.thursday, service0.calendar.thursday == 1); assertEquals(entry.friday, service0.calendar.friday == 1); assertEquals(entry.saturday, service0.calendar.saturday == 1); assertEquals(entry.sunday, service0.calendar.sunday == 1); assertEquals(checksum, network.checksum()); } /** simple test of adding a unidirectional trip with one frequency entry and no added stops */ @Test public void testAddUnidirectionalTripWithAddedStops () { assertEquals(1, network.transitLayer.tripPatterns.size()); AddTrips at = new AddTrips(); at.bidirectional = false; at.stops = Arrays.asList( new StopSpec("SINGLE_LINE:s1"), new StopSpec(-83.001, 40.012), new StopSpec("SINGLE_LINE:s3") ); at.mode = Route.BUS; AddTrips.PatternTimetable entry = new AddTrips.PatternTimetable(); entry.frequency = true; entry.headwaySecs = 900; entry.monday = entry.tuesday = entry.wednesday = entry.thursday = entry.friday = true; entry.saturday = entry.sunday = false; entry.hopTimes = new int[] { 120, 140 }; entry.dwellTimes = new int[] { 0, 30, 0 }; entry.startTime = 7 * 3600; entry.endTime = 10 * 3600; at.frequencies = Arrays.asList(entry); Scenario scenario = new Scenario(); scenario.modifications = Arrays.asList(at); TransportNetwork mod = scenario.applyToTransportNetwork(network); assertEquals(2, mod.transitLayer.tripPatterns.size()); // find the added trip pattern TripPattern pattern = mod.transitLayer.tripPatterns.stream() .filter(pat -> pat.tripSchedules.get(0).headwaySeconds != null) .findFirst() .orElse(null); // was it added? assertNotNull(pattern); // make sure the stops are in the right order assertEquals(3, pattern.stops.length); assertEquals("SINGLE_LINE:s1", mod.transitLayer.stopIdForIndex.get(pattern.stops[0])); assertEquals("SINGLE_LINE:s3", mod.transitLayer.stopIdForIndex.get(pattern.stops[2])); int createdVertex = mod.transitLayer.streetVertexForStop.get(pattern.stops[1]); VertexStore.Vertex v = mod.streetLayer.vertexStore.getCursor(createdVertex); // make sure the stop is in the right place assertEquals(40.012, v.getLat(), 1e-6); assertEquals(-83.001, v.getLon(), 1e-6); // make sure it's linked to the street network StreetRouter r = new StreetRouter(mod.streetLayer); r.distanceLimitMeters = 500; r.route(); assertTrue(r.getReachedVertices().size() > 5); // make sure it has a stop tree TIntIntMap stopTree = mod.transitLayer.stopTrees.get(pattern.stops[1]); assertNotNull(stopTree); assertFalse(stopTree.isEmpty()); // make sure it has transfers TIntList transfers = mod.transitLayer.transfersForStop.get(pattern.stops[1]); assertNotNull(transfers); // make sure that s2 is a target of a transfer boolean s2found = false; for (int i = 0; i < transfers.size(); i += 2) { if ("SINGLE_LINE:s2".equals(mod.transitLayer.stopIdForIndex.get(transfers.get(i)))) { s2found = true; break; } } assertTrue(s2found); // check the timetable assertEquals(1, pattern.tripSchedules.size()); TripSchedule ts = pattern.tripSchedules.get(0); assertEquals(3, ts.departures.length); assertEquals(3, ts.arrivals.length); assertEquals(0, ts.arrivals[0]); assertEquals(0, ts.departures[0]); assertEquals(120, ts.arrivals[1]); assertEquals(150, ts.departures[1]); assertEquals(290, ts.arrivals[2]); assertEquals(290, ts.departures[2]); // check the frequency assertArrayEquals(new int[] { entry.headwaySecs }, ts.headwaySeconds); assertArrayEquals(new int[] { entry.startTime }, ts.startTimes); assertArrayEquals(new int[] { entry.endTime }, ts.endTimes); // check the calendar Service service0 = mod.transitLayer.services.get(ts.serviceCode); assertEquals(entry.monday, service0.calendar.monday == 1); assertEquals(entry.tuesday, service0.calendar.tuesday == 1); assertEquals(entry.wednesday, service0.calendar.wednesday == 1); assertEquals(entry.thursday, service0.calendar.thursday == 1); assertEquals(entry.friday, service0.calendar.friday == 1); assertEquals(entry.saturday, service0.calendar.saturday == 1); assertEquals(entry.sunday, service0.calendar.sunday == 1); assertEquals(checksum, network.checksum()); } @After public void tearDown () { this.network = null; } }
Set origin in street router in AddTrip test
src/test/java/com/conveyal/r5/analyst/scenario/AddTripsTest.java
Set origin in street router in AddTrip test
<ide><path>rc/test/java/com/conveyal/r5/analyst/scenario/AddTripsTest.java <ide> assertEquals(checksum, network.checksum()); <ide> } <ide> <del> /** simple test of adding a unidirectional trip with one frequency entry and no added stops */ <add> /** <add> * Simple test of adding a unidirectional trip with one frequency entry and a newly created stop. <add> */ <ide> @Test <ide> public void testAddUnidirectionalTripWithAddedStops () { <ide> assertEquals(1, network.transitLayer.tripPatterns.size()); <ide> <ide> // make sure it's linked to the street network <ide> StreetRouter r = new StreetRouter(mod.streetLayer); <add> r.setOrigin(createdVertex); <ide> r.distanceLimitMeters = 500; <ide> r.route(); <ide>
Java
mit
3c10f1f7b905feb5b1f7c4b3a1d98048defda3a3
0
damianszczepanik/jenkins,tangkun75/jenkins,azweb76/jenkins,recena/jenkins,daniel-beck/jenkins,alvarolobato/jenkins,Jochen-A-Fuerbacher/jenkins,pjanouse/jenkins,evernat/jenkins,dariver/jenkins,ndeloof/jenkins,sathiya-mit/jenkins,christ66/jenkins,vjuranek/jenkins,Jimilian/jenkins,ajshastri/jenkins,azweb76/jenkins,amuniz/jenkins,Vlatombe/jenkins,aldaris/jenkins,amuniz/jenkins,azweb76/jenkins,varmenise/jenkins,ajshastri/jenkins,tangkun75/jenkins,azweb76/jenkins,oleg-nenashev/jenkins,FarmGeek4Life/jenkins,alvarolobato/jenkins,varmenise/jenkins,andresrc/jenkins,stephenc/jenkins,jpbriend/jenkins,gusreiber/jenkins,varmenise/jenkins,ydubreuil/jenkins,olivergondza/jenkins,Vlatombe/jenkins,Vlatombe/jenkins,protazy/jenkins,kohsuke/hudson,Jimilian/jenkins,ikedam/jenkins,pjanouse/jenkins,MichaelPranovich/jenkins_sc,bkmeneguello/jenkins,oleg-nenashev/jenkins,samatdav/jenkins,wuwen5/jenkins,alvarolobato/jenkins,pjanouse/jenkins,hplatou/jenkins,DanielWeber/jenkins,fbelzunc/jenkins,rsandell/jenkins,gusreiber/jenkins,ydubreuil/jenkins,ikedam/jenkins,jpbriend/jenkins,gitaccountforprashant/gittest,jglick/jenkins,recena/jenkins,ndeloof/jenkins,rsandell/jenkins,amuniz/jenkins,DanielWeber/jenkins,Ykus/jenkins,bpzhang/jenkins,batmat/jenkins,hplatou/jenkins,MarkEWaite/jenkins,godfath3r/jenkins,bpzhang/jenkins,vjuranek/jenkins,ndeloof/jenkins,fbelzunc/jenkins,sathiya-mit/jenkins,jglick/jenkins,dariver/jenkins,NehemiahMi/jenkins,christ66/jenkins,varmenise/jenkins,Jimilian/jenkins,recena/jenkins,ydubreuil/jenkins,tfennelly/jenkins,ikedam/jenkins,NehemiahMi/jenkins,andresrc/jenkins,jglick/jenkins,ajshastri/jenkins,ydubreuil/jenkins,escoem/jenkins,MarkEWaite/jenkins,wuwen5/jenkins,samatdav/jenkins,dennisjlee/jenkins,oleg-nenashev/jenkins,jenkinsci/jenkins,ydubreuil/jenkins,escoem/jenkins,protazy/jenkins,MarkEWaite/jenkins,Jochen-A-Fuerbacher/jenkins,jpbriend/jenkins,damianszczepanik/jenkins,vjuranek/jenkins,vjuranek/jenkins,pjanouse/jenkins,dennisjlee/jenkins,dennisjlee/jenkins,DanielWeber/jenkins,SebastienGllmt/jenkins,Ykus/jenkins,escoem/jenkins,ajshastri/jenkins,sathiya-mit/jenkins,escoem/jenkins,ikedam/jenkins,oleg-nenashev/jenkins,escoem/jenkins,lilyJi/jenkins,lilyJi/jenkins,protazy/jenkins,jglick/jenkins,FarmGeek4Life/jenkins,azweb76/jenkins,alvarolobato/jenkins,aldaris/jenkins,tfennelly/jenkins,rsandell/jenkins,ikedam/jenkins,SebastienGllmt/jenkins,alvarolobato/jenkins,SebastienGllmt/jenkins,sathiya-mit/jenkins,recena/jenkins,gitaccountforprashant/gittest,samatdav/jenkins,ikedam/jenkins,olivergondza/jenkins,MarkEWaite/jenkins,lilyJi/jenkins,azweb76/jenkins,Jimilian/jenkins,v1v/jenkins,daniel-beck/jenkins,dennisjlee/jenkins,MarkEWaite/jenkins,samatdav/jenkins,stephenc/jenkins,oleg-nenashev/jenkins,godfath3r/jenkins,gusreiber/jenkins,gitaccountforprashant/gittest,daniel-beck/jenkins,kohsuke/hudson,bpzhang/jenkins,hplatou/jenkins,amuniz/jenkins,bkmeneguello/jenkins,godfath3r/jenkins,ErikVerheul/jenkins,jglick/jenkins,ErikVerheul/jenkins,tfennelly/jenkins,jpbriend/jenkins,patbos/jenkins,ajshastri/jenkins,vjuranek/jenkins,bkmeneguello/jenkins,NehemiahMi/jenkins,damianszczepanik/jenkins,wuwen5/jenkins,jenkinsci/jenkins,gusreiber/jenkins,kohsuke/hudson,patbos/jenkins,hplatou/jenkins,amuniz/jenkins,escoem/jenkins,sathiya-mit/jenkins,tfennelly/jenkins,viqueen/jenkins,patbos/jenkins,gitaccountforprashant/gittest,batmat/jenkins,samatdav/jenkins,gusreiber/jenkins,Jimilian/jenkins,jglick/jenkins,kohsuke/hudson,damianszczepanik/jenkins,azweb76/jenkins,ajshastri/jenkins,damianszczepanik/jenkins,ErikVerheul/jenkins,jenkinsci/jenkins,ndeloof/jenkins,v1v/jenkins,olivergondza/jenkins,MichaelPranovich/jenkins_sc,patbos/jenkins,wuwen5/jenkins,dariver/jenkins,v1v/jenkins,hplatou/jenkins,olivergondza/jenkins,olivergondza/jenkins,FarmGeek4Life/jenkins,NehemiahMi/jenkins,viqueen/jenkins,patbos/jenkins,viqueen/jenkins,samatdav/jenkins,bkmeneguello/jenkins,viqueen/jenkins,alvarolobato/jenkins,aldaris/jenkins,viqueen/jenkins,andresrc/jenkins,godfath3r/jenkins,ErikVerheul/jenkins,ikedam/jenkins,recena/jenkins,MarkEWaite/jenkins,andresrc/jenkins,evernat/jenkins,Jochen-A-Fuerbacher/jenkins,lilyJi/jenkins,sathiya-mit/jenkins,fbelzunc/jenkins,bpzhang/jenkins,olivergondza/jenkins,wuwen5/jenkins,MichaelPranovich/jenkins_sc,MarkEWaite/jenkins,christ66/jenkins,christ66/jenkins,tfennelly/jenkins,godfath3r/jenkins,kohsuke/hudson,amuniz/jenkins,tangkun75/jenkins,SebastienGllmt/jenkins,lilyJi/jenkins,batmat/jenkins,tfennelly/jenkins,dariver/jenkins,bkmeneguello/jenkins,gitaccountforprashant/gittest,Ykus/jenkins,alvarolobato/jenkins,SebastienGllmt/jenkins,rlugojr/jenkins,evernat/jenkins,DanielWeber/jenkins,rsandell/jenkins,recena/jenkins,lilyJi/jenkins,christ66/jenkins,lilyJi/jenkins,Vlatombe/jenkins,daniel-beck/jenkins,rsandell/jenkins,Vlatombe/jenkins,bkmeneguello/jenkins,MichaelPranovich/jenkins_sc,bkmeneguello/jenkins,wuwen5/jenkins,fbelzunc/jenkins,wuwen5/jenkins,rsandell/jenkins,FarmGeek4Life/jenkins,christ66/jenkins,evernat/jenkins,varmenise/jenkins,DanielWeber/jenkins,SebastienGllmt/jenkins,Ykus/jenkins,dariver/jenkins,dariver/jenkins,gitaccountforprashant/gittest,rlugojr/jenkins,gitaccountforprashant/gittest,kohsuke/hudson,kohsuke/hudson,Jochen-A-Fuerbacher/jenkins,rlugojr/jenkins,bpzhang/jenkins,vjuranek/jenkins,MichaelPranovich/jenkins_sc,evernat/jenkins,damianszczepanik/jenkins,dennisjlee/jenkins,FarmGeek4Life/jenkins,tangkun75/jenkins,Jochen-A-Fuerbacher/jenkins,Jochen-A-Fuerbacher/jenkins,stephenc/jenkins,MichaelPranovich/jenkins_sc,rsandell/jenkins,stephenc/jenkins,NehemiahMi/jenkins,jenkinsci/jenkins,batmat/jenkins,Jochen-A-Fuerbacher/jenkins,stephenc/jenkins,escoem/jenkins,daniel-beck/jenkins,dennisjlee/jenkins,hplatou/jenkins,ndeloof/jenkins,recena/jenkins,ErikVerheul/jenkins,ndeloof/jenkins,andresrc/jenkins,bpzhang/jenkins,stephenc/jenkins,rsandell/jenkins,aldaris/jenkins,MarkEWaite/jenkins,jenkinsci/jenkins,jpbriend/jenkins,rlugojr/jenkins,FarmGeek4Life/jenkins,ajshastri/jenkins,rlugojr/jenkins,evernat/jenkins,tfennelly/jenkins,v1v/jenkins,oleg-nenashev/jenkins,pjanouse/jenkins,Ykus/jenkins,Vlatombe/jenkins,vjuranek/jenkins,ydubreuil/jenkins,rlugojr/jenkins,damianszczepanik/jenkins,protazy/jenkins,tangkun75/jenkins,pjanouse/jenkins,ydubreuil/jenkins,ErikVerheul/jenkins,batmat/jenkins,Ykus/jenkins,dariver/jenkins,tangkun75/jenkins,godfath3r/jenkins,oleg-nenashev/jenkins,ndeloof/jenkins,protazy/jenkins,Ykus/jenkins,v1v/jenkins,fbelzunc/jenkins,protazy/jenkins,batmat/jenkins,fbelzunc/jenkins,batmat/jenkins,andresrc/jenkins,fbelzunc/jenkins,olivergondza/jenkins,pjanouse/jenkins,NehemiahMi/jenkins,Jimilian/jenkins,andresrc/jenkins,godfath3r/jenkins,stephenc/jenkins,varmenise/jenkins,amuniz/jenkins,FarmGeek4Life/jenkins,sathiya-mit/jenkins,dennisjlee/jenkins,samatdav/jenkins,protazy/jenkins,patbos/jenkins,Vlatombe/jenkins,daniel-beck/jenkins,v1v/jenkins,jglick/jenkins,daniel-beck/jenkins,gusreiber/jenkins,kohsuke/hudson,ErikVerheul/jenkins,hplatou/jenkins,DanielWeber/jenkins,SebastienGllmt/jenkins,evernat/jenkins,daniel-beck/jenkins,patbos/jenkins,DanielWeber/jenkins,ikedam/jenkins,aldaris/jenkins,viqueen/jenkins,viqueen/jenkins,aldaris/jenkins,varmenise/jenkins,NehemiahMi/jenkins,Jimilian/jenkins,gusreiber/jenkins,jpbriend/jenkins,jenkinsci/jenkins,jpbriend/jenkins,v1v/jenkins,rlugojr/jenkins,tangkun75/jenkins,christ66/jenkins,bpzhang/jenkins,jenkinsci/jenkins,damianszczepanik/jenkins,MichaelPranovich/jenkins_sc,jenkinsci/jenkins,aldaris/jenkins
package hudson.init.impl; import hudson.init.Initializer; import jenkins.model.Jenkins; import org.kohsuke.stapler.WebApp; import org.kohsuke.stapler.compression.CompressionFilter; import org.kohsuke.stapler.compression.UncaughtExceptionHandler; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.kohsuke.stapler.Stapler; /** * @author Kohsuke Kawaguchi */ public class InstallUncaughtExceptionHandler { @Initializer public static void init(final Jenkins j) throws IOException { CompressionFilter.setUncaughtExceptionHandler(j.servletContext, new UncaughtExceptionHandler() { @Override public void reportException(Throwable e, ServletContext context, HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException { req.setAttribute("javax.servlet.error.exception",e); try { WebApp.get(j.servletContext).getSomeStapler() .invoke(req,rsp, Jenkins.getInstance(), "/oops"); } catch (ServletException x) { if (!Stapler.isSocketException(x)) { throw x; } } catch (IOException x) { if (!Stapler.isSocketException(x)) { throw x; } } } }); Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); } /** An UncaughtExceptionHandler that just logs the exception */ private static class DefaultUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { private static final Logger LOGGER = Logger.getLogger(InstallUncaughtExceptionHandler.class.getName()); @Override public void uncaughtException(Thread t, Throwable ex) { // if this was an OutOfMemoryError then all bets about logging are off - but in the absence of anything else... LOGGER.log(Level.SEVERE, "A thread (" + t.getName() + '/' + t.getId() + ") died unexepectedly due to an uncaught exception, this may leave your Jenkins in a bad way and is usually indicitive of a bug in the code.", ex); } } }
core/src/main/java/hudson/init/impl/InstallUncaughtExceptionHandler.java
package hudson.init.impl; import hudson.init.Initializer; import jenkins.model.Jenkins; import org.kohsuke.stapler.WebApp; import org.kohsuke.stapler.compression.CompressionFilter; import org.kohsuke.stapler.compression.UncaughtExceptionHandler; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import org.kohsuke.stapler.Stapler; /** * @author Kohsuke Kawaguchi */ public class InstallUncaughtExceptionHandler { @Initializer public static void init(final Jenkins j) throws IOException { CompressionFilter.setUncaughtExceptionHandler(j.servletContext, new UncaughtExceptionHandler() { @Override public void reportException(Throwable e, ServletContext context, HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException { req.setAttribute("javax.servlet.error.exception",e); try { WebApp.get(j.servletContext).getSomeStapler() .invoke(req,rsp, Jenkins.getInstance(), "/oops"); } catch (ServletException x) { if (!Stapler.isSocketException(x)) { throw x; } } catch (IOException x) { if (!Stapler.isSocketException(x)) { throw x; } } } }); } }
[FIXED JENKINS-33395] install an uncaught exception handler
core/src/main/java/hudson/init/impl/InstallUncaughtExceptionHandler.java
[FIXED JENKINS-33395] install an uncaught exception handler
<ide><path>ore/src/main/java/hudson/init/impl/InstallUncaughtExceptionHandler.java <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> import java.io.IOException; <add>import java.util.logging.Level; <add>import java.util.logging.Logger; <add> <ide> import org.kohsuke.stapler.Stapler; <ide> <ide> /** <ide> } <ide> } <ide> }); <add> Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); <add> } <add> <add> /** An UncaughtExceptionHandler that just logs the exception */ <add> private static class DefaultUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { <add> <add> private static final Logger LOGGER = Logger.getLogger(InstallUncaughtExceptionHandler.class.getName()); <add> <add> @Override <add> public void uncaughtException(Thread t, Throwable ex) { <add> // if this was an OutOfMemoryError then all bets about logging are off - but in the absence of anything else... <add> LOGGER.log(Level.SEVERE, <add> "A thread (" + t.getName() + '/' + t.getId() <add> + ") died unexepectedly due to an uncaught exception, this may leave your Jenkins in a bad way and is usually indicitive of a bug in the code.", <add> ex); <add> } <add> <ide> } <ide> }
JavaScript
agpl-3.0
dc5e21b9b62282c15a82e0811d3c13092c0f759d
0
RAPD/RAPD,RAPD/RAPD,RAPD/RAPD,RAPD/RAPD,RAPD/RAPD
var express = require('express'); var router = express.Router(); var mongoose = require('../models/mongoose'); const config = require('../config'); // Redis const Redis = require('ioredis'); var redis_client = new Redis(config.redis_connection); // routes that end with jobs // ---------------------------------------------------- // These are redis-based queries // route to return all current requests (GET http://localhost:3000/api/requests) router.route('/jobs/submit') // add a request for a process to launch (accessed at PUT api/requests) .put(function(req, res) { let request = req.body.request; // Add _id to process is not present if (! request.process.result_id) { request.process.result_id = new mongoose.mongo.ObjectId().toHexString(); } console.log("REQUEST", request); redis_client.lpush('RAPD_JOBS', JSON.stringify(request), function(err, queue_length) { if (err) { console.error(err); res.status(500).json({ success: false, error: err }); } else { console.log('Job added to RAPD_JOBS queue length:', queue_length); res.status(200).json({ success: true, queue_length: queue_length }); } }); }); // End .put(function(req,res) { module.exports = router;
src/services/rest/routes/jobs.js
var express = require('express'); var router = express.Router(); var mongoose = require('../models/mongoose'); const config = require('../config'); // Redis const Redis = require('ioredis'); var redis_client = new Redis(config.redis_connection); // routes that end with jobs // ---------------------------------------------------- // These are redis-based queries // route to return all current requests (GET http://localhost:3000/api/requests) router.route('/jobs/submit') // add a request for a process to launch (accessed at PUT api/requests) .put(function(req, res) { let request = req.body.request; // Add _id to process is not present if (! request.process.result_id) { request.process.result_id = new mongoose.mongo.ObjectId(); } console.log("REQUEST", request); redis_client.lpush('RAPD_JOBS', JSON.stringify(request), function(err, queue_length) { if (err) { console.error(err); res.status(500).json({ success: false, error: err }); } else { console.log('Job added to RAPD_JOBS queue length:', queue_length); res.status(200).json({ success: true, queue_length: queue_length }); } }); }); // End .put(function(req,res) { module.exports = router;
Turn ObjectId to string for Sending...
src/services/rest/routes/jobs.js
Turn ObjectId to string for Sending...
<ide><path>rc/services/rest/routes/jobs.js <ide> <ide> // Add _id to process is not present <ide> if (! request.process.result_id) { <del> request.process.result_id = new mongoose.mongo.ObjectId(); <add> request.process.result_id = new mongoose.mongo.ObjectId().toHexString(); <ide> } <ide> <ide> console.log("REQUEST", request);
Java
mit
a2619879fe7156ea8b225ee16ce0bb8c709cd63f
0
curtisullerich/attendance,curtisullerich/attendance,curtisullerich/attendance
package edu.iastate.music.marching.attendance.controllers; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.Set; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.code.twig.ObjectDatastore; import com.google.common.collect.Sets; import edu.iastate.music.marching.attendance.model.Message; import edu.iastate.music.marching.attendance.model.MessageThread; import edu.iastate.music.marching.attendance.model.ModelFactory; import edu.iastate.music.marching.attendance.model.User; public class MessagingController extends AbstractController { private DataTrain train; public MessagingController(DataTrain dataTrain) { this.train = dataTrain; } /** * Note that this does not store the message thread! * * @param initial_participants * @return */ public MessageThread createMessageThread(User... initial_participants) { MessageThread thread = ModelFactory.newMessageThread(); if (initial_participants != null) { thread.setParticipants(Sets.newHashSet(initial_participants)); } // Default to resolved, no messages yet thread.setResolved(true); // train.getDataStore().store(thread); return thread; } public MessageThread addMessage(MessageThread thread, User sender, String message) { if (thread == null) throw new IllegalArgumentException("Null thread given"); if (sender == null) throw new IllegalArgumentException("Null sender given"); // Add sender as participant in conversation Set<User> thread_participants = thread.getParticipants(); if (thread_participants == null) { thread_participants = new HashSet<User>(); thread.setParticipants(thread_participants); } thread_participants.add(sender); // Add actual message List<Message> messages = thread.getMessages(); if (messages == null) { messages = new ArrayList<Message>(); thread.setMessages(messages); } messages.add(0, ModelFactory.newMessage(sender, message)); // Always unresolved after adding a message thread.setResolved(false); update(thread); return thread; } public void update(MessageThread thread) { this.train.getDataStore().update(thread); } public List<MessageThread> get(User involved) { ObjectDatastore od = this.train.getDataStore(); // TODO https://github.com/curtisullerich/attendance/issues/112 // Daniel: Have to use Key types for an IN filter for now, // newer versions of twig-persist support using actual objects however Key k = od.associatedKey(involved); return this.train .find(MessageThread.class) .addFilter(MessageThread.FIELD_PARTICIPANTS, FilterOperator.IN, Arrays.asList(new Key[] { k })).returnAll().now(); } public List<MessageThread> get(User involved, boolean resolved) { ObjectDatastore od = this.train.getDataStore(); // TODO https://github.com/curtisullerich/attendance/issues/112 // Daniel: Have to use Key types for an IN filter for now, // newer versions of twig-persist support using actual objects however Key k = od.associatedKey(involved); return this.train .find(MessageThread.class) .addFilter(MessageThread.FIELD_PARTICIPANTS, FilterOperator.IN, Arrays.asList(new Key[] { k })) .addFilter(MessageThread.FIELD_RESOLVED, FilterOperator.EQUAL, resolved).returnAll().now(); } public List<MessageThread> get(boolean resolved) { return this.train .find(MessageThread.class) .addFilter(MessageThread.FIELD_RESOLVED, FilterOperator.EQUAL, resolved).returnAll().now(); } public MessageThread get(long id) { return this.train.getDataStore().load( this.train.getTie(MessageThread.class, id)); } public List<MessageThread> getAll() { return this.train.find(MessageThread.class).returnAll().now(); } /** * Returns the most recent message added to this MessageThread. * * @author curtisu * @return */ public Message getMostRecent(MessageThread mt) { List<Message> messages = mt.getMessages(); if (messages.size() == 0) { return null; } Message mostRecent = messages.get(0); for (Message m : messages) { if (m.getTimestamp().after(mostRecent.getTimestamp())) { mostRecent = m; } } return mostRecent; } void scrubParticipant(User participant) { List<MessageThread> involved = this.get(participant); for (MessageThread thread : involved) { ListIterator<Message> iter = thread.getMessages().listIterator(); while (iter.hasNext()) { Message message = iter.next(); if (message != null && message.getAuthor() == participant) { iter.remove(); } } thread.getParticipants().remove(participant); } } void delete(MessageThread mt) { this.train.getDataStore().delete(mt); } }
src/main/edu/iastate/music/marching/attendance/controllers/MessagingController.java
package edu.iastate.music.marching.attendance.controllers; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.Set; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.code.twig.ObjectDatastore; import com.google.common.collect.Sets; import edu.iastate.music.marching.attendance.model.Message; import edu.iastate.music.marching.attendance.model.MessageThread; import edu.iastate.music.marching.attendance.model.ModelFactory; import edu.iastate.music.marching.attendance.model.User; public class MessagingController extends AbstractController { private DataTrain train; public MessagingController(DataTrain dataTrain) { this.train = dataTrain; } public MessageThread createMessageThread(User... initial_participants) { MessageThread thread = ModelFactory.newMessageThread(); if (initial_participants != null) { thread.setParticipants(Sets.newHashSet(initial_participants)); } // Default to resolved, no messages yet thread.setResolved(true); train.getDataStore().store(thread); return thread; } public MessageThread addMessage(MessageThread thread, User sender, String message) { if (thread == null) throw new IllegalArgumentException("Null thread given"); if (sender == null) throw new IllegalArgumentException("Null sender given"); // Add sender as participant in conversation Set<User> thread_participants = thread.getParticipants(); if (thread_participants == null) { thread_participants = new HashSet<User>(); thread.setParticipants(thread_participants); } thread_participants.add(sender); // Add actual message List<Message> messages = thread.getMessages(); if (messages == null) { messages = new ArrayList<Message>(); thread.setMessages(messages); } messages.add(0, ModelFactory.newMessage(sender, message)); // Always unresolved after adding a message thread.setResolved(false); update(thread); return thread; } public void update(MessageThread thread) { this.train.getDataStore().update(thread); } public List<MessageThread> get(User involved) { ObjectDatastore od = this.train.getDataStore(); // TODO https://github.com/curtisullerich/attendance/issues/112 // Daniel: Have to use Key types for an IN filter for now, // newer versions of twig-persist support using actual objects however Key k = od.associatedKey(involved); return this.train .find(MessageThread.class) .addFilter(MessageThread.FIELD_PARTICIPANTS, FilterOperator.IN, Arrays.asList(new Key[] { k })).returnAll().now(); } public List<MessageThread> get(User involved, boolean resolved) { ObjectDatastore od = this.train.getDataStore(); // TODO https://github.com/curtisullerich/attendance/issues/112 // Daniel: Have to use Key types for an IN filter for now, // newer versions of twig-persist support using actual objects however Key k = od.associatedKey(involved); return this.train .find(MessageThread.class) .addFilter(MessageThread.FIELD_PARTICIPANTS, FilterOperator.IN, Arrays.asList(new Key[] { k })) .addFilter(MessageThread.FIELD_RESOLVED, FilterOperator.EQUAL, resolved).returnAll().now(); } public List<MessageThread> get(boolean resolved) { return this.train .find(MessageThread.class) .addFilter(MessageThread.FIELD_RESOLVED, FilterOperator.EQUAL, resolved).returnAll().now(); } public MessageThread get(long id) { return this.train.getDataStore().load( this.train.getTie(MessageThread.class, id)); } public List<MessageThread> getAll() { return this.train.find(MessageThread.class).returnAll().now(); } /** * Returns the most recent message added to this MessageThread. * * @author curtisu * @return */ public Message getMostRecent(MessageThread mt) { List<Message> messages = mt.getMessages(); if (messages.size() == 0) { return null; } Message mostRecent = messages.get(0); for (Message m : messages) { if (m.getTimestamp().after(mostRecent.getTimestamp())) { mostRecent = m; } } return mostRecent; } void scrubParticipant(User participant) { List<MessageThread> involved = this.get(participant); for (MessageThread thread : involved) { ListIterator<Message> iter = thread.getMessages().listIterator(); while (iter.hasNext()) { Message message = iter.next(); if (message != null && message.getAuthor() == participant) { iter.remove(); } } thread.getParticipants().remove(participant); } } void delete(MessageThread mt) { this.train.getDataStore().delete(mt); } }
#42 removed store() call from createMessageThread()
src/main/edu/iastate/music/marching/attendance/controllers/MessagingController.java
#42 removed store() call from createMessageThread()
<ide><path>rc/main/edu/iastate/music/marching/attendance/controllers/MessagingController.java <ide> this.train = dataTrain; <ide> } <ide> <add> /** <add> * Note that this does not store the message thread! <add> * <add> * @param initial_participants <add> * @return <add> */ <ide> public MessageThread createMessageThread(User... initial_participants) { <ide> <ide> MessageThread thread = ModelFactory.newMessageThread(); <ide> <ide> // Default to resolved, no messages yet <ide> thread.setResolved(true); <del> train.getDataStore().store(thread); <add> // train.getDataStore().store(thread); <ide> <ide> return thread; <ide> }
Java
apache-2.0
142e5c2f57eb7c6341c4a2100708c2ea88ee821e
0
slipstream/SlipStreamServer,slipstream/SlipStreamServer,slipstream/SlipStreamServer,slipstream/SlipStreamServer
package com.sixsq.slipstream.connector.stratuslab; /* * +=================================================================+ * SlipStream Server (WAR) * ===== * Copyright (C) 2013 SixSq Sarl (sixsq.com) * ===== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -=================================================================- */ import com.sixsq.slipstream.connector.UserParametersFactoryBase; import com.sixsq.slipstream.exceptions.ValidationException; import com.sixsq.slipstream.persistence.ParameterType; public class StratusLabUserParametersFactory extends UserParametersFactoryBase { public static String MARKETPLACE_ENDPOINT_PARAMETER_NAME = "marketplace.endpoint"; public static String MESSAGING_TYPE_PARAMETER_NAME = "messaging.type"; public static String MESSAGING_ENDPOINT_PARAMETER_NAME = "messaging.endpoint"; public static String MESSAGING_QUEUE_PARAMETER_NAME = "messaging.queue"; public StratusLabUserParametersFactory(String connectorInstanceName) throws ValidationException { super(connectorInstanceName); } @Override protected void initReferenceParameters() throws ValidationException { putMandatoryParameter(KEY_PARAMETER_NAME, "StratusLab account username", ParameterType.RestrictedString); putMandatoryPasswordParameter(SECRET_PARAMETER_NAME, "StratusLab account password"); } }
jar/src/main/java/com/sixsq/slipstream/connector/stratuslab/StratusLabUserParametersFactory.java
package com.sixsq.slipstream.connector.stratuslab; /* * +=================================================================+ * SlipStream Server (WAR) * ===== * Copyright (C) 2013 SixSq Sarl (sixsq.com) * ===== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -=================================================================- */ import com.sixsq.slipstream.connector.UserParametersFactoryBase; import com.sixsq.slipstream.exceptions.ValidationException; import com.sixsq.slipstream.persistence.ParameterType; public class StratusLabUserParametersFactory extends UserParametersFactoryBase { public static String KEY_PARAMETER_NAME = "username"; public static String SECRET_PARAMETER_NAME = "password"; public static String ORCHESTRATOR_INSTANCE_TYPE_PARAMETER_NAME = "orchestrator.instance.type"; public static String MARKETPLACE_ENDPOINT_PARAMETER_NAME = "marketplace.endpoint"; public static String MESSAGING_TYPE_PARAMETER_NAME = "messaging.type"; public static String MESSAGING_ENDPOINT_PARAMETER_NAME = "messaging.endpoint"; public static String MESSAGING_QUEUE_PARAMETER_NAME = "messaging.queue"; public static String UPDATE_CLIENTURL_PARAMETER_NAME = "update.clienturl"; public StratusLabUserParametersFactory(String connectorInstanceName) throws ValidationException { super(connectorInstanceName); } @Override protected void initReferenceParameters() throws ValidationException { putMandatoryParameter(KEY_PARAMETER_NAME, "StratusLab account username", ParameterType.RestrictedString); putMandatoryPasswordParameter(SECRET_PARAMETER_NAME, "StratusLab account password"); } }
Minor
jar/src/main/java/com/sixsq/slipstream/connector/stratuslab/StratusLabUserParametersFactory.java
Minor
<ide><path>ar/src/main/java/com/sixsq/slipstream/connector/stratuslab/StratusLabUserParametersFactory.java <ide> <ide> public class StratusLabUserParametersFactory extends UserParametersFactoryBase { <ide> <del> public static String KEY_PARAMETER_NAME = "username"; <del> public static String SECRET_PARAMETER_NAME = "password"; <del> public static String ORCHESTRATOR_INSTANCE_TYPE_PARAMETER_NAME = "orchestrator.instance.type"; <ide> public static String MARKETPLACE_ENDPOINT_PARAMETER_NAME = "marketplace.endpoint"; <ide> public static String MESSAGING_TYPE_PARAMETER_NAME = "messaging.type"; <ide> public static String MESSAGING_ENDPOINT_PARAMETER_NAME = "messaging.endpoint"; <ide> public static String MESSAGING_QUEUE_PARAMETER_NAME = "messaging.queue"; <del> public static String UPDATE_CLIENTURL_PARAMETER_NAME = "update.clienturl"; <ide> <ide> <ide> public StratusLabUserParametersFactory(String connectorInstanceName) throws ValidationException {
Java
lgpl-2.1
074d1348cbdad22299ad2c6d2b03db23086a5de3
0
justincc/intermine,zebrafishmine/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,tomck/intermine,kimrutherford/intermine,joshkh/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,JoeCarlson/intermine,elsiklab/intermine,joshkh/intermine,zebrafishmine/intermine,elsiklab/intermine,kimrutherford/intermine,kimrutherford/intermine,zebrafishmine/intermine,tomck/intermine,tomck/intermine,justincc/intermine,tomck/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,justincc/intermine,zebrafishmine/intermine,justincc/intermine,elsiklab/intermine,zebrafishmine/intermine,zebrafishmine/intermine,JoeCarlson/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,joshkh/intermine,zebrafishmine/intermine,justincc/intermine,joshkh/intermine,elsiklab/intermine,tomck/intermine,JoeCarlson/intermine,JoeCarlson/intermine,JoeCarlson/intermine,kimrutherford/intermine,zebrafishmine/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,elsiklab/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,kimrutherford/intermine,elsiklab/intermine,tomck/intermine,justincc/intermine,kimrutherford/intermine,JoeCarlson/intermine,tomck/intermine,tomck/intermine,joshkh/intermine,elsiklab/intermine,justincc/intermine,JoeCarlson/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine
package org.intermine; import java.io.BufferedReader; import java.security.Principal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Enumeration; import java.util.Locale; import java.util.Map; import java.util.Vector; import javax.servlet.RequestDispatcher; import javax.servlet.ServletInputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * Mock for testing methods that handle requests. * * @author Alex Kalderimis */ public class MockHttpRequest implements HttpServletRequest { private final Map<String, String[]> headers, parameters; private final String method; private static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); public MockHttpRequest(String method, Map<String, String[]> headers, Map<String, String[]> parameters) { if (headers == null || parameters == null || method == null) { throw new NullPointerException(); } this.method = method; this.headers = headers; this.parameters = parameters; } @Override public String getAuthType() { throw new UnmockedException(); } @Override public long getDateHeader(String name) { String val = getHeader(name); if (val != null) { try { return dateFormat.parse(val).getTime(); } catch (ParseException e) { // Ignore. } } return 0L; } @Override public String getHeader(String name) { for (String k: headers.keySet()) { if (k.equalsIgnoreCase(name)) { return headers.get(k)[0]; } } return null; } @Override public Enumeration<String> getHeaders(String name) { Vector<String> v = new Vector<String>(); for (String k: headers.keySet()) { if (k.equalsIgnoreCase(name)) { v.addAll(Arrays.asList(headers.get(k))); } } return v.elements(); } @Override public Enumeration<String> getHeaderNames() { Vector<String> v = new Vector<String>(headers.keySet()); return v.elements(); } @Override public int getIntHeader(String name) { return Integer.valueOf(getHeader(name)); } @Override public String getMethod() { return method; } private String pathInfo = null; @Override public String getPathInfo() { return pathInfo; } @Override public String getPathTranslated() { return getPathInfo(); } @Override public String getContextPath() { throw new UnmockedException(); } @Override public String getQueryString() { throw new UnmockedException(); } @Override public String getRemoteUser() { throw new UnmockedException(); } @Override public String getRequestedSessionId() { throw new UnmockedException(); } @Override public String getRequestURI() { throw new UnmockedException(); } @Override public StringBuffer getRequestURL() { throw new UnmockedException(); } @Override public String getServletPath() { throw new UnmockedException(); } @Override public HttpSession getSession() { throw new UnmockedException(); } @Override public HttpSession getSession(boolean create) { throw new UnmockedException(); } @Override public boolean isRequestedSessionIdFromCookie() { throw new UnmockedException(); } @Override public boolean isRequestedSessionIdFromUrl() { throw new UnmockedException(); } @Override public boolean isRequestedSessionIdFromURL() { throw new UnmockedException(); } @Override public boolean isUserInRole(String role) { throw new UnmockedException(); } @Override public Principal getUserPrincipal() { throw new UnmockedException(); } // From ServletRequest @Override public Object getAttribute(String name) { throw new UnmockedException(); } @Override public Enumeration<String> getAttributeNames() { throw new UnmockedException(); } @Override public String getContentType() { throw new UnmockedException(); } @Override public ServletInputStream getInputStream() { throw new UnmockedException(); } @Override public String getLocalAddr() { throw new UnmockedException(); } @Override public Locale getLocale() { throw new UnmockedException(); } @Override public Enumeration<Locale> getLocales() { throw new UnmockedException(); } @Override public String getLocalName() { throw new UnmockedException(); } @Override public int getLocalPort() { throw new UnmockedException(); } @Override public String getParameter(String name) { String[] all = parameters.get(name); if (all != null) { return all[0]; } return null; } @Override public Map<String, String[]> getParameterMap() { return parameters; } @Override public Enumeration<String> getParameterNames() { Vector<String> v = new Vector<String>(parameters.keySet()); return v.elements(); } @Override public String[] getParameterValues(String name) { return parameters.get(name); } @Override public String getProtocol() { throw new UnmockedException(); } @Override public BufferedReader getReader() { throw new UnmockedException(); } @Override public String getRealPath(String path) { throw new UnmockedException(); } @Override public String getRemoteAddr() { throw new UnmockedException(); } @Override public String getRemoteHost() { throw new UnmockedException(); } @Override public int getRemotePort() { throw new UnmockedException(); } @Override public String getScheme() { throw new UnmockedException(); } @Override public String getServerName() { throw new UnmockedException(); } @Override public int getServerPort() { throw new UnmockedException(); } @Override public void setCharacterEncoding(String name) { throw new UnmockedException(); } @Override public RequestDispatcher getRequestDispatcher(String arg0) { throw new UnmockedException(); } @Override public void setAttribute(String arg0, Object arg1) { throw new UnmockedException(); } @Override public boolean isRequestedSessionIdValid() { throw new UnmockedException(); } @Override public Cookie[] getCookies() { throw new UnmockedException(); } @Override public boolean isSecure() { throw new UnmockedException(); } @Override public void removeAttribute(String arg0) { throw new UnmockedException(); } @Override public String getCharacterEncoding() { throw new UnmockedException(); } @Override public int getContentLength() { throw new UnmockedException(); } public static class UnmockedException extends RuntimeException { private static final long serialVersionUID = 962046232556269912L; public UnmockedException() { super("No implementation provided for " + new Exception().getStackTrace()[1].getMethodName()); } } }
intermine/web/test/src/org/intermine/MockHttpRequest.java
package org.intermine; import java.io.BufferedReader; import java.security.Principal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Enumeration; import java.util.Locale; import java.util.Map; import java.util.Vector; import javax.servlet.RequestDispatcher; import javax.servlet.ServletInputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * Mock for testing methods that handle requests. * * @author Alex Kalderimis */ public class MockHttpRequest implements HttpServletRequest { private final Map<String, String[]> headers, parameters; private final String method; private static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); public MockHttpRequest(String method, Map<String, String[]> headers, Map<String, String[]> parameters) { if (headers == null || parameters == null || method == null) { throw new NullPointerException(); } this.method = method; this.headers = headers; this.parameters = parameters; } @Override public String getAuthType() { throw new UnmockedException(); } @Override public long getDateHeader(String name) { String val = getHeader(name); if (val != null) { try { return dateFormat.parse(val).getTime(); } catch (ParseException e) { // Ignore. } } return 0L; } @Override public String getHeader(String name) { for (String k: headers.keySet()) { if (k.equalsIgnoreCase(name)) { return headers.get(k)[0]; } } return null; } @Override public Enumeration<String> getHeaders(String name) { Vector<String> v = new Vector<String>(); for (String k: headers.keySet()) { if (k.equalsIgnoreCase(name)) { v.addAll(Arrays.asList(headers.get(k))); } } return v.elements(); } @Override public Enumeration<String> getHeaderNames() { Vector<String> v = new Vector<String>(headers.keySet()); return v.elements(); } @Override public int getIntHeader(String name) { return Integer.valueOf(getHeader(name)); } @Override public String getMethod() { return method; } private String pathInfo = null; @Override public String getPathInfo() { return pathInfo; } @Override public String getPathTranslated() { return getPathInfo(); } @Override public String getContextPath() { throw new UnmockedException(); } @Override public String getQueryString() { throw new UnmockedException(); } @Override public String getRemoteUser() { throw new UnmockedException(); } @Override public String getRequestedSessionId() { throw new UnmockedException(); } @Override public String getRequestURI() { throw new UnmockedException(); } @Override public StringBuffer getRequestURL() { throw new UnmockedException(); } @Override public String getServletPath() { throw new UnmockedException(); } @Override public HttpSession getSession() { throw new UnmockedException(); } @Override public HttpSession getSession(boolean create) { throw new UnmockedException(); } @Override public boolean isRequestedSessionIdFromCookie() { throw new UnmockedException(); } @Override public boolean isRequestedSessionIdFromUrl() { throw new UnmockedException(); } @Override public boolean isRequestedSessionIdFromURL() { throw new UnmockedException(); } @Override public boolean isUserInRole(String role) { throw new UnmockedException(); } @Override public Principal getUserPrincipal() { throw new UnmockedException(); } // From ServletRequest @Override public Object getAttribute(String name) { throw new UnmockedException(); } @Override public Enumeration<String> getAttributeNames() { throw new UnmockedException(); } @Override public String getContentType() { throw new UnmockedException(); } @Override public ServletInputStream getInputStream() { throw new UnmockedException(); } @Override public String getLocalAddr() { throw new UnmockedException(); } @Override public Locale getLocale() { throw new UnmockedException(); } @Override public Enumeration<Locale> getLocales() { throw new UnmockedException(); } @Override public String getLocalName() { throw new UnmockedException(); } @Override public int getLocalPort() { throw new UnmockedException(); } @Override public String getParameter(String name) { return parameters.get(name)[0]; } @Override public Map<String, String[]> getParameterMap() { return parameters; } @Override public Enumeration<String> getParameterNames() { Vector<String> v = new Vector<String>(parameters.keySet()); return v.elements(); } @Override public String[] getParameterValues(String name) { return parameters.get(name); } @Override public String getProtocol() { throw new UnmockedException(); } @Override public BufferedReader getReader() { throw new UnmockedException(); } @Override public String getRealPath(String path) { throw new UnmockedException(); } @Override public String getRemoteAddr() { throw new UnmockedException(); } @Override public String getRemoteHost() { throw new UnmockedException(); } @Override public int getRemotePort() { throw new UnmockedException(); } @Override public String getScheme() { throw new UnmockedException(); } @Override public String getServerName() { throw new UnmockedException(); } @Override public int getServerPort() { throw new UnmockedException(); } @Override public void setCharacterEncoding(String name) { throw new UnmockedException(); } @Override public RequestDispatcher getRequestDispatcher(String arg0) { throw new UnmockedException(); } @Override public void setAttribute(String arg0, Object arg1) { throw new UnmockedException(); } @Override public boolean isRequestedSessionIdValid() { throw new UnmockedException(); } @Override public Cookie[] getCookies() { throw new UnmockedException(); } @Override public boolean isSecure() { throw new UnmockedException(); } @Override public void removeAttribute(String arg0) { throw new UnmockedException(); } @Override public String getCharacterEncoding() { throw new UnmockedException(); } @Override public int getContentLength() { throw new UnmockedException(); } public static class UnmockedException extends RuntimeException { public UnmockedException() { super("No implementation provided for " + new Exception().getStackTrace()[1].getMethodName()); } } }
Fixed null-pointer error.
intermine/web/test/src/org/intermine/MockHttpRequest.java
Fixed null-pointer error.
<ide><path>ntermine/web/test/src/org/intermine/MockHttpRequest.java <ide> <ide> @Override <ide> public String getParameter(String name) { <del> return parameters.get(name)[0]; <add> String[] all = parameters.get(name); <add> if (all != null) { <add> return all[0]; <add> } <add> return null; <ide> } <ide> <ide> @Override <ide> <ide> public static class UnmockedException extends RuntimeException <ide> { <add> private static final long serialVersionUID = 962046232556269912L; <add> <ide> public UnmockedException() { <ide> super("No implementation provided for " + new Exception().getStackTrace()[1].getMethodName()); <ide> }
Java
mit
e7cc26c72bc14cba74c230bfe7f523966579565c
0
carlos-sancho-ramirez/android-java-langbook,carlos-sancho-ramirez/android-java-langbook
package sword.langbook3.android; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ClickableSpan; import android.util.SparseArray; import android.util.SparseIntArray; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import sword.collections.ImmutableIntList; import sword.collections.ImmutableIntSet; import sword.collections.ImmutableIntSetBuilder; import sword.collections.ImmutableList; import sword.langbook3.android.AcceptationDetailsActivityState.IntrinsicStates; import sword.langbook3.android.AcceptationDetailsAdapter.AcceptationNavigableItem; import sword.langbook3.android.AcceptationDetailsAdapter.AgentNavigableItem; import sword.langbook3.android.AcceptationDetailsAdapter.HeaderItem; import sword.langbook3.android.AcceptationDetailsAdapter.NonNavigableItem; import sword.langbook3.android.AcceptationDetailsAdapter.RuleNavigableItem; import sword.langbook3.android.LangbookDbSchema.AcceptationsTable; import sword.langbook3.android.LangbookDbSchema.AgentSetsTable; import sword.langbook3.android.LangbookDbSchema.AgentsTable; import sword.langbook3.android.LangbookDbSchema.AlphabetsTable; import sword.langbook3.android.LangbookDbSchema.BunchAcceptationsTable; import sword.langbook3.android.LangbookDbSchema.BunchConceptsTable; import sword.langbook3.android.LangbookDbSchema.BunchSetsTable; import sword.langbook3.android.LangbookDbSchema.CorrelationArraysTable; import sword.langbook3.android.LangbookDbSchema.CorrelationsTable; import sword.langbook3.android.LangbookDbSchema.LanguagesTable; import sword.langbook3.android.LangbookDbSchema.QuestionFieldSets; import sword.langbook3.android.LangbookDbSchema.QuizDefinitionsTable; import sword.langbook3.android.LangbookDbSchema.RuledAcceptationsTable; import sword.langbook3.android.LangbookDbSchema.StringQueriesTable; import sword.langbook3.android.LangbookDbSchema.SymbolArraysTable; import sword.langbook3.android.LangbookDbSchema.Tables; import sword.langbook3.android.db.Database; import sword.langbook3.android.db.DbExporter; import sword.langbook3.android.db.DbInsertQuery; import sword.langbook3.android.db.DbQuery; import sword.langbook3.android.db.DbResult; import sword.langbook3.android.db.DbUpdateQuery; import static sword.langbook3.android.LangbookDatabase.addAcceptationInBunch; import static sword.langbook3.android.LangbookDatabase.removeAcceptationFromBunch; import static sword.langbook3.android.LangbookDbInserter.insertBunchConcept; import static sword.langbook3.android.LangbookDeleter.deleteBunchConceptForConcept; import static sword.langbook3.android.LangbookReadableDatabase.conceptFromAcceptation; import static sword.langbook3.android.LangbookReadableDatabase.readConceptText; import static sword.langbook3.android.db.DbIdColumn.idColumnName; public final class AcceptationDetailsActivity extends Activity implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, DialogInterface.OnClickListener { private static final int REQUEST_CODE_LINKED_ACCEPTATION = 1; private static final int REQUEST_CODE_PICK_ACCEPTATION = 2; private static final int REQUEST_CODE_PICK_BUNCH = 3; private static final int REQUEST_CODE_PICK_SUPERTYPE = 4; private interface ArgKeys { String STATIC_ACCEPTATION = BundleKeys.STATIC_ACCEPTATION; String DYNAMIC_ACCEPTATION = BundleKeys.DYNAMIC_ACCEPTATION; } private interface SavedKeys { String STATE = "cSt"; } // Specifies the alphabet the user would like to see if possible. // TODO: This should be a shared preference static final int preferredAlphabet = 4; private int _staticAcceptation; private int _concept; private ImmutableIntSet _bunchesWhereIncluded; private AcceptationResult _definition; private AcceptationDetailsActivityState _state; private boolean _shouldShowBunchChildrenQuizMenuOption; private ListView _listView; private AcceptationDetailsAdapter _listAdapter; public static void open(Context context, int staticAcceptation, int dynamicAcceptation) { Intent intent = new Intent(context, AcceptationDetailsActivity.class); intent.putExtra(ArgKeys.STATIC_ACCEPTATION, staticAcceptation); intent.putExtra(ArgKeys.DYNAMIC_ACCEPTATION, dynamicAcceptation); context.startActivity(intent); } static final class CorrelationHolder { final int id; final SparseArray<String> texts; CorrelationHolder(int id, SparseArray<String> texts) { this.id = id; this.texts = texts; } } private List<CorrelationHolder> readCorrelationArray(SQLiteDatabase db, int acceptation) { final AcceptationsTable acceptations = Tables.acceptations; // J0 final CorrelationArraysTable correlationArrays = Tables.correlationArrays; // J1 final CorrelationsTable correlations = Tables.correlations; // J2 final SymbolArraysTable symbolArrays = Tables.symbolArrays; // J3 Cursor cursor = db.rawQuery( "SELECT" + " J1." + correlationArrays.columns().get(correlationArrays.getArrayPositionColumnIndex()).name() + ",J2." + correlations.columns().get(correlations.getCorrelationIdColumnIndex()).name() + ",J2." + correlations.columns().get(correlations.getAlphabetColumnIndex()).name() + ",J3." + symbolArrays.columns().get(symbolArrays.getStrColumnIndex()).name() + " FROM " + acceptations.name() + " AS J0" + " JOIN " + correlationArrays.name() + " AS J1 ON J0." + acceptations.columns().get(acceptations.getCorrelationArrayColumnIndex()).name() + "=J1." + correlationArrays.columns().get(correlationArrays.getArrayIdColumnIndex()).name() + " JOIN " + correlations.name() + " AS J2 ON J1." + correlationArrays.columns().get(correlationArrays.getCorrelationColumnIndex()).name() + "=J2." + correlations.columns().get(correlations.getCorrelationIdColumnIndex()).name() + " JOIN " + symbolArrays.name() + " AS J3 ON J2." + correlations.columns().get(correlations.getSymbolArrayColumnIndex()).name() + "=J3." + idColumnName + " WHERE J0." + idColumnName + "=?" + " ORDER BY" + " J1." + correlationArrays.columns().get(correlationArrays.getArrayPositionColumnIndex()).name() + ",J2." + correlations.columns().get(correlations.getAlphabetColumnIndex()).name() , new String[] { Integer.toString(acceptation) }); final ArrayList<CorrelationHolder> result = new ArrayList<>(); if (cursor != null) { try { if (cursor.moveToFirst()) { SparseArray<String> corr = new SparseArray<>(); int pos = cursor.getInt(0); int correlationId = cursor.getInt(1); if (pos != result.size()) { throw new AssertionError("Expected position " + result.size() + ", but it was " + pos); } corr.put(cursor.getInt(2), cursor.getString(3)); while(cursor.moveToNext()) { int newPos = cursor.getInt(0); if (newPos != pos) { result.add(new CorrelationHolder(correlationId, corr)); correlationId = cursor.getInt(1); corr = new SparseArray<>(); } pos = newPos; if (newPos != result.size()) { throw new AssertionError("Expected position " + result.size() + ", but it was " + pos); } corr.put(cursor.getInt(2), cursor.getString(3)); } result.add(new CorrelationHolder(correlationId, corr)); } } finally { cursor.close(); } } return result; } private static final class LanguageResult { final int acceptation; final int language; final String text; LanguageResult(int acceptation, int language, String text) { this.acceptation = acceptation; this.language = language; this.text = text; } } private LanguageResult readLanguageFromAlphabet(SQLiteDatabase db, int alphabet) { final AcceptationsTable acceptations = Tables.acceptations; // J0 final AlphabetsTable alphabets = Tables.alphabets; final StringQueriesTable strings = Tables.stringQueries; Cursor cursor = db.rawQuery( "SELECT" + " J1." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + ",J1." + idColumnName + ",J2." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + ",J2." + strings.columns().get(strings.getStringColumnIndex()).name() + " FROM " + alphabets.name() + " AS J0" + " JOIN " + acceptations.name() + " AS J1 ON J0." + alphabets.columns().get(alphabets.getLanguageColumnIndex()).name() + "=J1." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + " JOIN " + strings.name() + " AS J2 ON J1." + idColumnName + "=J2." + strings.columns().get(strings.getDynamicAcceptationColumnIndex()).name() + " WHERE J0." + idColumnName + "=?", new String[] { Integer.toString(alphabet) }); int lang = -1; int langAcc = -1; String text = null; try { cursor.moveToFirst(); lang = cursor.getInt(0); langAcc = cursor.getInt(1); int firstAlphabet = cursor.getInt(2); text = cursor.getString(3); while (firstAlphabet != preferredAlphabet && cursor.moveToNext()) { if (cursor.getInt(2) == preferredAlphabet) { lang = cursor.getInt(0); langAcc = cursor.getInt(1); firstAlphabet = preferredAlphabet; text = cursor.getString(3); } } } finally { cursor.close(); } return new LanguageResult(langAcc, lang, text); } private static final class AcceptationResult { final int acceptation; final String text; AcceptationResult(int acceptation, String text) { this.acceptation = acceptation; this.text = text; } } private AcceptationResult readDefinition(SQLiteDatabase db, int acceptation) { final AcceptationsTable acceptations = Tables.acceptations; final BunchConceptsTable bunchConcepts = Tables.bunchConcepts; final StringQueriesTable strings = Tables.stringQueries; Cursor cursor = db.rawQuery( "SELECT" + " J2." + idColumnName + ",J3." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + ",J3." + strings.columns().get(strings.getStringColumnIndex()).name() + " FROM " + acceptations.name() + " AS J0" + " JOIN " + bunchConcepts.name() + " AS J1 ON J0." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + "=J1." + bunchConcepts.columns().get(bunchConcepts.getConceptColumnIndex()).name() + " JOIN " + acceptations.name() + " AS J2 ON J1." + bunchConcepts.columns().get(bunchConcepts.getBunchColumnIndex()).name() + "=J2." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + " JOIN " + strings.name() + " AS J3 ON J2." + idColumnName + "=J3." + strings.columns().get(strings.getDynamicAcceptationColumnIndex()).name() + " WHERE J0." + idColumnName + "=?", new String[] { Integer.toString(acceptation) }); AcceptationResult result = null; if (cursor != null) { try { if (cursor.moveToFirst()) { int acc = cursor.getInt(0); int firstAlphabet = cursor.getInt(1); String text = cursor.getString(2); while (firstAlphabet != preferredAlphabet && cursor.moveToNext()) { if (cursor.getInt(1) == preferredAlphabet) { acc = cursor.getInt(0); text = cursor.getString(2); break; } } result = new AcceptationResult(acc, text); } } finally { cursor.close(); } } return result; } private AcceptationResult[] readSubTypes(SQLiteDatabase db, int acceptation, int language) { final AcceptationsTable acceptations = Tables.acceptations; final AlphabetsTable alphabets = Tables.alphabets; final BunchConceptsTable bunchConcepts = Tables.bunchConcepts; final StringQueriesTable strings = Tables.stringQueries; Cursor cursor = db.rawQuery( "SELECT" + " J2." + idColumnName + ",J3." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + ",J3." + strings.columns().get(strings.getStringColumnIndex()).name() + " FROM " + acceptations.name() + " AS J0" + " JOIN " + bunchConcepts.name() + " AS J1 ON J0." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + "=J1." + bunchConcepts.columns().get(bunchConcepts.getBunchColumnIndex()).name() + " JOIN " + acceptations.name() + " AS J2 ON J1." + bunchConcepts.columns().get(bunchConcepts.getConceptColumnIndex()).name() + "=J2." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + " JOIN " + strings.name() + " AS J3 ON J2." + idColumnName + "=J3." + strings.columns().get(strings.getDynamicAcceptationColumnIndex()).name() + " JOIN " + alphabets.name() + " AS J4 ON J3." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + "=J4." + idColumnName + " WHERE J0." + idColumnName + "=?" + " AND J4." + alphabets.columns().get(alphabets.getLanguageColumnIndex()).name() + "=?" + " ORDER BY J2." + idColumnName, new String[] { Integer.toString(acceptation), Integer.toString(language) }); if (cursor != null) { try { if (cursor.moveToFirst()) { final ArrayList<AcceptationResult> result = new ArrayList<>(); int acc = cursor.getInt(0); int alphabet = cursor.getInt(1); String text = cursor.getString(2); while (cursor.moveToNext()) { if (cursor.getInt(0) == acc) { if (alphabet != preferredAlphabet && cursor.getInt(1) == preferredAlphabet) { alphabet = preferredAlphabet; text = cursor.getString(2); } } else { result.add(new AcceptationResult(acc, text)); acc = cursor.getInt(0); alphabet = cursor.getInt(1); text = cursor.getString(2); } } result.add(new AcceptationResult(acc, text)); return result.toArray(new AcceptationResult[result.size()]); } } finally { cursor.close(); } } return new AcceptationResult[0]; } private static final class BunchInclusionResult { final int acceptation; final boolean dynamic; final String text; BunchInclusionResult(int acceptation, boolean dynamic, String text) { this.acceptation = acceptation; this.dynamic = dynamic; this.text = text; } } private BunchInclusionResult[] readBunchesWhereIncluded(SQLiteDatabase db, int acceptation) { final AcceptationsTable acceptations = Tables.acceptations; final BunchAcceptationsTable bunchAcceptations = Tables.bunchAcceptations; final StringQueriesTable strings = Tables.stringQueries; final ImmutableIntSetBuilder bunchSetBuilder = new ImmutableIntSetBuilder(); Cursor cursor = db.rawQuery( "SELECT" + " J0." + bunchAcceptations.columns().get(bunchAcceptations.getBunchColumnIndex()).name() + ",J1." + idColumnName + ",J2." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + ",J2." + strings.columns().get(strings.getStringColumnIndex()).name() + ",J0." + bunchAcceptations.columns().get(bunchAcceptations.getAgentSetColumnIndex()).name() + " FROM " + bunchAcceptations.name() + " AS J0" + " JOIN " + acceptations.name() + " AS J1 ON J0." + bunchAcceptations.columns().get(bunchAcceptations.getBunchColumnIndex()).name() + "=J1." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + " JOIN " + strings.name() + " AS J2 ON J1." + idColumnName + "=J2." + strings.columns().get(strings.getDynamicAcceptationColumnIndex()).name() + " WHERE J0." + bunchAcceptations.columns().get(bunchAcceptations.getAcceptationColumnIndex()).name() + "=?", new String[] { Integer.toString(acceptation) }); if (cursor != null) { try { if (cursor.moveToFirst()) { final int nullAgentSet = Tables.agentSets.nullReference(); ArrayList<BunchInclusionResult> result = new ArrayList<>(); int bunch = cursor.getInt(0); int acc = cursor.getInt(1); int firstAlphabet = cursor.getInt(2); String text = cursor.getString(3); int agentSet = cursor.getInt(4); while (cursor.moveToNext()) { if (firstAlphabet != preferredAlphabet && cursor.getInt(2) == preferredAlphabet) { acc = cursor.getInt(1); text = cursor.getString(3); firstAlphabet = preferredAlphabet; } if (bunch != cursor.getInt(0)) { bunchSetBuilder.add(bunch); result.add(new BunchInclusionResult(acc, agentSet != nullAgentSet, text)); bunch = cursor.getInt(0); agentSet = cursor.getInt(4); acc = cursor.getInt(1); firstAlphabet = cursor.getInt(2); text = cursor.getString(3); } } bunchSetBuilder.add(bunch); result.add(new BunchInclusionResult(acc, agentSet != nullAgentSet, text)); return result.toArray(new BunchInclusionResult[result.size()]); } } finally { cursor.close(); } } _bunchesWhereIncluded = bunchSetBuilder.build(); return new BunchInclusionResult[0]; } private static final class BunchChildResult { final int acceptation; final boolean dynamic; final String text; BunchChildResult(int acceptation, boolean dynamic, String text) { this.acceptation = acceptation; this.dynamic = dynamic; this.text = text; } } private BunchChildResult[] readBunchChildren(SQLiteDatabase db, int acceptation) { final AcceptationsTable acceptations = Tables.acceptations; final BunchAcceptationsTable bunchAcceptations = Tables.bunchAcceptations; final StringQueriesTable strings = Tables.stringQueries; Cursor cursor = db.rawQuery( "SELECT" + " J1." + bunchAcceptations.columns().get(bunchAcceptations.getAcceptationColumnIndex()).name() + ",J2." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + ",J2." + strings.columns().get(strings.getStringColumnIndex()).name() + ",J1." + bunchAcceptations.columns().get(bunchAcceptations.getAgentSetColumnIndex()).name() + " FROM " + acceptations.name() + " AS J0" + " JOIN " + bunchAcceptations.name() + " AS J1 ON J0." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + "=J1." + bunchAcceptations.columns().get(bunchAcceptations.getBunchColumnIndex()).name() + " JOIN " + strings.name() + " AS J2 ON J1." + bunchAcceptations.columns().get(bunchAcceptations.getAcceptationColumnIndex()).name() + "=J2." + strings.columns().get(strings.getDynamicAcceptationColumnIndex()).name() + " WHERE J0." + idColumnName + "=?" + " ORDER BY J1." + bunchAcceptations.columns().get(bunchAcceptations.getAcceptationColumnIndex()).name(), new String[] { Integer.toString(acceptation) }); if (cursor != null) { try { if (cursor.moveToFirst()) { final int nullAgentSet = Tables.agentSets.nullReference(); ArrayList<BunchChildResult> result = new ArrayList<>(); int acc = cursor.getInt(0); int alphabet = cursor.getInt(1); String text = cursor.getString(2); int agentSet = cursor.getInt(3); while (cursor.moveToNext()) { if (acc == cursor.getInt(0)) { if (alphabet != preferredAlphabet && cursor.getInt(2) == preferredAlphabet) { alphabet = preferredAlphabet; text = cursor.getString(2); } } else { result.add(new BunchChildResult(acc, agentSet != nullAgentSet, text)); acc = cursor.getInt(0); alphabet = cursor.getInt(1); text = cursor.getString(2); agentSet = cursor.getInt(3); } } result.add(new BunchChildResult(acc, agentSet != nullAgentSet, text)); return result.toArray(new BunchChildResult[result.size()]); } } finally { cursor.close(); } } return new BunchChildResult[0]; } private static final class SynonymTranslationResult { final int acceptation; final int language; final String text; SynonymTranslationResult(int acceptation, int language, String text) { this.acceptation = acceptation; this.language = language; this.text = text; } } private ImmutableList<SynonymTranslationResult> readSynonymsAndTranslations(DbExporter.Database db, int acceptation) { final AcceptationsTable acceptations = Tables.acceptations; final AlphabetsTable alphabets = Tables.alphabets; final StringQueriesTable strings = Tables.stringQueries; final LanguagesTable languages = Tables.languages; final int accOffset = acceptations.columns().size(); final int stringsOffset = accOffset * 2; final int alphabetsOffset = stringsOffset + strings.columns().size(); final int languagesOffset = alphabetsOffset + alphabets.columns().size(); final DbQuery query = new DbQuery.Builder(acceptations) .join(acceptations, acceptations.getConceptColumnIndex(), acceptations.getConceptColumnIndex()) .join(strings, acceptations.columns().size() + acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .join(alphabets, stringsOffset + strings.getStringAlphabetColumnIndex(), alphabets.getIdColumnIndex()) .join(languages, alphabetsOffset + alphabets.getLanguageColumnIndex(), languages.getIdColumnIndex()) .where(acceptations.getIdColumnIndex(), acceptation) .whereColumnValueMatch(alphabetsOffset + alphabets.getIdColumnIndex(), languagesOffset + languages.getMainAlphabetColumnIndex()) .select(accOffset + acceptations.getIdColumnIndex(), languagesOffset + languages.getIdColumnIndex(), stringsOffset + strings.getStringColumnIndex()); final DbResult result = db.select(query); final ImmutableList.Builder<SynonymTranslationResult> builder = new ImmutableList.Builder<>(result.getRemainingRows()); try { while (result.hasNext()) { final DbResult.Row row = result.next(); final int accId = row.get(0).toInt(); if (accId != acceptation) { builder.add(new SynonymTranslationResult(accId, row.get(1).toInt(), row.get(2).toText())); } } } finally { result.close(); } return builder.build(); } private static final class MorphologyResult { final int agent; final int dynamicAcceptation; final int rule; final String ruleText; final String text; MorphologyResult(int agent, int dynamicAcceptation, int rule, String ruleText, String text) { this.agent = agent; this.dynamicAcceptation = dynamicAcceptation; this.rule = rule; this.ruleText = ruleText; this.text = text; } } private MorphologyResult[] readMorphologies(SQLiteDatabase db, int acceptation) { final AcceptationsTable acceptations = Tables.acceptations; final AgentsTable agents = Tables.agents; final StringQueriesTable strings = Tables.stringQueries; final RuledAcceptationsTable ruledAcceptations = Tables.ruledAcceptations; Cursor cursor = db.rawQuery( "SELECT" + " J0." + idColumnName + ",J3." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + ",J1." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + ",J1." + strings.columns().get(strings.getStringColumnIndex()).name() + ",J4." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + ",J4." + strings.columns().get(strings.getStringColumnIndex()).name() + ",J2." + idColumnName + " FROM " + ruledAcceptations.name() + " AS J0" + " JOIN " + strings.name() + " AS J1 ON J0." + idColumnName + "=J1." + strings.columns().get(strings.getDynamicAcceptationColumnIndex()).name() + " JOIN " + agents.name() + " AS J2 ON J0." + ruledAcceptations.columns().get(ruledAcceptations.getAgentColumnIndex()).name() + "=J2." + idColumnName + " JOIN " + acceptations.name() + " AS J3 ON J2." + agents.columns().get(agents.getRuleColumnIndex()).name() + "=J3." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + " JOIN " + strings.name() + " AS J4 ON J3." + idColumnName + "=J4." + strings.columns().get(strings.getDynamicAcceptationColumnIndex()).name() + " WHERE J0." + ruledAcceptations.columns().get(ruledAcceptations.getAcceptationColumnIndex()).name() + "=?" + " AND J1." + strings.columns().get(strings.getMainAcceptationColumnIndex()).name() + "=?" + " ORDER BY J0." + idColumnName, new String[] { Integer.toString(acceptation) , Integer.toString(acceptation)}); if (cursor != null) { try { if (cursor.moveToFirst()) { ArrayList<MorphologyResult> result = new ArrayList<>(); int acc = cursor.getInt(0); int rule = cursor.getInt(1); int alphabet = cursor.getInt(2); String text = cursor.getString(3); int ruleAlphabet = cursor.getInt(4); String ruleText = cursor.getString(5); int agent = cursor.getInt(6); while (cursor.moveToNext()) { if (cursor.getInt(0) == acc) { if (alphabet != preferredAlphabet && cursor.getInt(2) == preferredAlphabet) { alphabet = preferredAlphabet; text = cursor.getString(3); } if (ruleAlphabet != preferredAlphabet && cursor.getInt(4) == preferredAlphabet) { ruleAlphabet = preferredAlphabet; ruleText = cursor.getString(5); } } else { result.add(new MorphologyResult(agent, acc, rule, ruleText, text)); acc = cursor.getInt(0); rule = cursor.getInt(1); alphabet = cursor.getInt(2); text = cursor.getString(3); ruleAlphabet = cursor.getInt(4); ruleText = cursor.getString(5); agent = cursor.getInt(6); } } result.add(new MorphologyResult(agent, acc, rule, ruleText, text)); return result.toArray(new MorphologyResult[result.size()]); } } finally { cursor.close(); } } return new MorphologyResult[0]; } private static class InvolvedAgentResult { interface Flags { int target = 1; int source = 2; int diff = 4; int rule = 8; int processed = 16; } final int agentId; final int flags; InvolvedAgentResult(int agentId, int flags) { this.agentId = agentId; this.flags = flags; } } private int[] readAgentsWhereAccIsTarget(SQLiteDatabase db, int staticAcceptation) { final AcceptationsTable acceptations = Tables.acceptations; final AgentsTable agents = Tables.agents; final Cursor cursor = db.rawQuery(" SELECT J1." + idColumnName + " FROM " + acceptations.name() + " AS J0" + " JOIN " + agents.name() + " AS J1 ON J0." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + "=J1." + agents.columns().get(agents.getTargetBunchColumnIndex()).name() + " WHERE J0." + idColumnName + "=?", new String[] { Integer.toString(staticAcceptation)}); if (cursor != null) { try { if (cursor.moveToFirst()) { int[] result = new int[cursor.getCount()]; int index = 0; do { result[index++] = cursor.getInt(0); } while (cursor.moveToNext()); return result; } } finally { cursor.close(); } } return new int[0]; } private int[] readAgentsWhereAccIsSource(SQLiteDatabase db, int staticAcceptation) { final AcceptationsTable acceptations = Tables.acceptations; final AgentsTable agents = Tables.agents; final BunchSetsTable bunchSets = Tables.bunchSets; final Cursor cursor = db.rawQuery(" SELECT J2." + idColumnName + " FROM " + acceptations.name() + " AS J0" + " JOIN " + bunchSets.name() + " AS J1 ON J0." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + "=J1." + bunchSets.columns().get(bunchSets.getBunchColumnIndex()).name() + " JOIN " + agents.name() + " AS J2 ON J1." + bunchSets.columns().get(bunchSets.getSetIdColumnIndex()).name() + "=J2." + agents.columns().get(agents.getSourceBunchSetColumnIndex()).name() + " WHERE J0." + idColumnName + "=?", new String[] { Integer.toString(staticAcceptation)}); if (cursor != null) { try { if (cursor.moveToFirst()) { int[] result = new int[cursor.getCount()]; int index = 0; do { result[index++] = cursor.getInt(0); } while (cursor.moveToNext()); return result; } } finally { cursor.close(); } } return new int[0]; } private int[] readAgentsWhereAccIsRule(SQLiteDatabase db, int staticAcceptation) { final AcceptationsTable acceptations = Tables.acceptations; final AgentsTable agents = Tables.agents; final Cursor cursor = db.rawQuery(" SELECT J1." + idColumnName + " FROM " + acceptations.name() + " AS J0" + " JOIN " + agents.name() + " AS J1 ON J0." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + "=J1." + agents.columns().get(agents.getRuleColumnIndex()).name() + " WHERE J0." + idColumnName + "=?", new String[] { Integer.toString(staticAcceptation)}); if (cursor != null) { try { if (cursor.moveToFirst()) { int[] result = new int[cursor.getCount()]; int index = 0; do { result[index++] = cursor.getInt(0); } while (cursor.moveToNext()); return result; } } finally { cursor.close(); } } return new int[0]; } private int[] readAgentsWhereAccIsProcessed(SQLiteDatabase db, int staticAcceptation) { final AgentsTable agents = Tables.agents; final BunchAcceptationsTable bunchAcceptations = Tables.bunchAcceptations; final AgentSetsTable agentSets = Tables.agentSets; final Cursor cursor = db.rawQuery(" SELECT J1." + agentSets.columns().get(agentSets.getAgentColumnIndex()).name() + " FROM " + bunchAcceptations.name() + " AS J0" + " JOIN " + agentSets.name() + " AS J1 ON J0." + bunchAcceptations.columns().get(bunchAcceptations.getAgentSetColumnIndex()).name() + "=J1." + agentSets.columns().get(agentSets.getSetIdColumnIndex()).name() + " WHERE J0." + bunchAcceptations.columns().get(bunchAcceptations.getAcceptationColumnIndex()).name() + "=?", new String[] { Integer.toString(staticAcceptation)}); if (cursor != null) { try { if (cursor.moveToFirst()) { ArrayList<Integer> result = new ArrayList<>(); do { final int id = cursor.getInt(0); if (id != agents.nullReference()) { result.add(id); } } while (cursor.moveToNext()); int[] intResult = new int[result.size()]; int index = 0; for (int value : result) { intResult[index++] = value; } return intResult; } } finally { cursor.close(); } } return new int[0]; } private InvolvedAgentResult[] readInvolvedAgents(SQLiteDatabase db, int staticAcceptation) { final SparseIntArray flags = new SparseIntArray(); for (int agentId : readAgentsWhereAccIsTarget(db, staticAcceptation)) { flags.put(agentId, flags.get(agentId) | InvolvedAgentResult.Flags.target); } for (int agentId : readAgentsWhereAccIsSource(db, staticAcceptation)) { flags.put(agentId, flags.get(agentId) | InvolvedAgentResult.Flags.source); } // TODO: Diff not implemented as right now it is impossible for (int agentId : readAgentsWhereAccIsRule(db, staticAcceptation)) { flags.put(agentId, flags.get(agentId) | InvolvedAgentResult.Flags.rule); } for (int agentId : readAgentsWhereAccIsProcessed(db, staticAcceptation)) { flags.put(agentId, flags.get(agentId) | InvolvedAgentResult.Flags.processed); } final int count = flags.size(); final InvolvedAgentResult[] result = new InvolvedAgentResult[count]; for (int i = 0; i < count; i++) { result[i] = new InvolvedAgentResult(flags.keyAt(i), flags.valueAt(i)); } return result; } private class CorrelationSpan extends ClickableSpan { final int id; final int start; final int end; CorrelationSpan(int id, int start, int end) { if (start < 0 || end < start) { throw new IllegalArgumentException(); } this.id = id; this.start = start; this.end = end; } @Override public void onClick(View view) { CorrelationDetailsActivity.open(AcceptationDetailsActivity.this, id); } } static void composeCorrelation(SparseArray<String> correlation, StringBuilder sb) { final int correlationSize = correlation.size(); for (int i = 0; i < correlationSize; i++) { if (i != 0) { sb.append('/'); } sb.append(correlation.valueAt(i)); } } private AcceptationDetailsAdapter.Item[] getAdapterItems(int staticAcceptation) { SQLiteDatabase db = DbManager.getInstance().getReadableDatabase(); final ArrayList<AcceptationDetailsAdapter.Item> result = new ArrayList<>(); result.add(new HeaderItem("Displaying details for acceptation " + staticAcceptation)); final StringBuilder sb = new StringBuilder("Correlation: "); List<CorrelationHolder> correlationArray = readCorrelationArray(db, staticAcceptation); List<CorrelationSpan> correlationSpans = new ArrayList<>(); for (int i = 0; i < correlationArray.size(); i++) { if (i != 0) { sb.append(" - "); } final CorrelationHolder holder = correlationArray.get(i); final SparseArray<String> correlation = holder.texts; final int correlationSize = correlation.size(); int startIndex = -1; if (correlationSize > 1) { startIndex = sb.length(); } composeCorrelation(correlation, sb); if (startIndex >= 0) { correlationSpans.add(new CorrelationSpan(holder.id, startIndex, sb.length())); } } SpannableString spannableCorrelations = new SpannableString(sb.toString()); for (CorrelationSpan span : correlationSpans) { spannableCorrelations.setSpan(span, span.start, span.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } result.add(new NonNavigableItem(spannableCorrelations)); final LanguageResult languageResult = readLanguageFromAlphabet(db, correlationArray.get(0).texts.keyAt(0)); result.add(new NonNavigableItem("Language: " + languageResult.text)); final SparseArray<String> languageStrs = new SparseArray<>(); languageStrs.put(languageResult.language, languageResult.text); _definition = readDefinition(db, staticAcceptation); if (_definition != null) { result.add(new AcceptationNavigableItem(_definition.acceptation, "Type of: " + _definition.text, false)); } boolean subTypeFound = false; for (AcceptationResult subType : readSubTypes(db, staticAcceptation, languageResult.language)) { if (!subTypeFound) { result.add(new HeaderItem("Subtypes")); subTypeFound = true; } result.add(new AcceptationNavigableItem(subType.acceptation, subType.text, false)); } final ImmutableList<SynonymTranslationResult> synonymTranslationResults = readSynonymsAndTranslations(DbManager.getInstance().getDatabase(), staticAcceptation); boolean synonymFound = false; for (SynonymTranslationResult r : synonymTranslationResults) { if (r.language == languageResult.language) { if (!synonymFound) { result.add(new HeaderItem("Synonyms")); synonymFound = true; } result.add(new AcceptationNavigableItem(r.acceptation, r.text, false)); } } boolean translationFound = false; for (SynonymTranslationResult r : synonymTranslationResults) { final int language = r.language; if (language != languageResult.language) { if (!translationFound) { result.add(new HeaderItem("Translations")); translationFound = true; } String langStr = languageStrs.get(language); if (langStr == null) { langStr = readConceptText(DbManager.getInstance().getDatabase(), language, preferredAlphabet); languageStrs.put(language, langStr); } result.add(new AcceptationNavigableItem(r.acceptation, "" + langStr + " -> " + r.text, false)); } } boolean parentBunchFound = false; for (BunchInclusionResult r : readBunchesWhereIncluded(db, staticAcceptation)) { if (!parentBunchFound) { result.add(new HeaderItem("Bunches where included")); parentBunchFound = true; } result.add(new AcceptationNavigableItem(AcceptationDetailsAdapter.ItemTypes.BUNCH_WHERE_INCLUDED, r.acceptation, r.text, r.dynamic)); } boolean morphologyFound = false; MorphologyResult[] morphologyResults = readMorphologies(db, staticAcceptation); for (MorphologyResult r : morphologyResults) { if (!morphologyFound) { result.add(new HeaderItem("Morphologies")); morphologyFound = true; } result.add(new RuleNavigableItem(r.dynamicAcceptation, r.ruleText + " -> " + r.text)); } boolean bunchChildFound = false; for (BunchChildResult r : readBunchChildren(db, staticAcceptation)) { if (!bunchChildFound) { result.add(new HeaderItem("Acceptations included in this bunch")); bunchChildFound = true; _shouldShowBunchChildrenQuizMenuOption = true; } result.add(new AcceptationNavigableItem(AcceptationDetailsAdapter.ItemTypes.ACCEPTATION_INCLUDED, r.acceptation, r.text, r.dynamic)); } boolean agentFound = false; for (InvolvedAgentResult r : readInvolvedAgents(db, staticAcceptation)) { if (!agentFound) { result.add(new HeaderItem("Involved agents")); agentFound = true; } final StringBuilder s = new StringBuilder("Agent #"); s.append(r.agentId).append(" ("); s.append(((r.flags & InvolvedAgentResult.Flags.target) != 0)? 'T' : '-'); s.append(((r.flags & InvolvedAgentResult.Flags.source) != 0)? 'S' : '-'); s.append(((r.flags & InvolvedAgentResult.Flags.diff) != 0)? 'D' : '-'); s.append(((r.flags & InvolvedAgentResult.Flags.rule) != 0)? 'R' : '-'); s.append(((r.flags & InvolvedAgentResult.Flags.processed) != 0)? 'P' : '-'); s.append(')'); result.add(new AgentNavigableItem(r.agentId, s.toString())); } for (MorphologyResult r : morphologyResults) { if (!agentFound) { result.add(new HeaderItem("Involved agents")); agentFound = true; } final StringBuilder s = new StringBuilder("Agent #"); s.append(r.agent).append(" (").append(r.ruleText).append(')'); result.add(new AgentNavigableItem(r.agent, s.toString())); } return result.toArray(new AcceptationDetailsAdapter.Item[result.size()]); } private void updateAdapter() { _listAdapter = new AcceptationDetailsAdapter(getAdapterItems(_staticAcceptation)); _listView.setAdapter(_listAdapter); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.acceptation_details_activity); if (!getIntent().hasExtra(ArgKeys.STATIC_ACCEPTATION)) { throw new IllegalArgumentException("staticAcceptation not provided"); } if (savedInstanceState != null) { _state = savedInstanceState.getParcelable(SavedKeys.STATE); } if (_state == null) { _state = new AcceptationDetailsActivityState(); } _staticAcceptation = getIntent().getIntExtra(ArgKeys.STATIC_ACCEPTATION, 0); _concept = conceptFromAcceptation(DbManager.getInstance().getDatabase(), _staticAcceptation); _listView = findViewById(R.id.listView); if (_concept != 0) { updateAdapter(); _listView.setOnItemClickListener(this); _listView.setOnItemLongClickListener(this); switch (_state.getIntrinsicState()) { case IntrinsicStates.DELETE_ACCEPTATION: showDeleteConfirmationDialog(); break; case IntrinsicStates.DELETE_SUPERTYPE: showDeleteSupertypeConfirmationDialog(); break; case IntrinsicStates.DELETING_FROM_BUNCH: showDeleteFromBunchConfirmationDialog(); break; case IntrinsicStates.DELETING_ACCEPTATION_FROM_BUNCH: showDeleteAcceptationFromBunchConfirmationDialog(); break; case IntrinsicStates.LINKING_CONCEPT: showLinkModeSelectorDialog(); break; } } else { finish(); } } @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { _listAdapter.getItem(position).navigate(this); } @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { // For now, as the only valuable action per item is 'delete', no // contextual menu is displayed and confirmation dialog is prompted directly. // // This routine may be valuable while there is only one enabled item. // For multiple, the action mode for the list view should be enabled // instead to apply the same action to multiple items at the same time. final AcceptationDetailsAdapter.Item item = _listAdapter.getItem(position); if (item.getItemType() == AcceptationDetailsAdapter.ItemTypes.BUNCH_WHERE_INCLUDED) { AcceptationNavigableItem it = (AcceptationNavigableItem) item; if (!it.isDynamic()) { final int bunch = conceptFromAcceptation(DbManager.getInstance().getDatabase(), it.getId()); _state.setDeleteBunchTarget(new DisplayableItem(bunch, it.getText().toString())); showDeleteFromBunchConfirmationDialog(); } return true; } else if (item.getItemType() == AcceptationDetailsAdapter.ItemTypes.ACCEPTATION_INCLUDED) { AcceptationNavigableItem it = (AcceptationNavigableItem) item; if (!it.isDynamic()) { _state.setDeleteAcceptationFromBunch(new DisplayableItem(it.getId(), it.getText().toString())); showDeleteAcceptationFromBunchConfirmationDialog(); } return true; } return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { final MenuInflater inflater = new MenuInflater(this); if (_shouldShowBunchChildrenQuizMenuOption) { inflater.inflate(R.menu.acceptation_details_activity_bunch_children_quiz, menu); } inflater.inflate(R.menu.acceptation_details_activity_link_options, menu); if (_definition == null) { inflater.inflate(R.menu.acceptation_details_activity_include_supertype, menu); } else { inflater.inflate(R.menu.acceptation_details_activity_delete_supertype, menu); } inflater.inflate(R.menu.acceptation_details_activity_delete_acceptation, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menuItemBunchChildrenQuiz: QuizSelectorActivity.open(this, _concept); return true; case R.id.menuItemLinkConcept: AcceptationPickerActivity.open(this, REQUEST_CODE_LINKED_ACCEPTATION, _concept); return true; case R.id.menuItemIncludeAcceptation: AcceptationPickerActivity.open(this, REQUEST_CODE_PICK_ACCEPTATION); return true; case R.id.menuItemIncludeInBunch: AcceptationPickerActivity.open(this, REQUEST_CODE_PICK_BUNCH); return true; case R.id.menuItemDeleteAcceptation: _state.setDeletingAcceptation(); showDeleteConfirmationDialog(); return true; case R.id.menuItemIncludeSupertype: AcceptationPickerActivity.open(this, REQUEST_CODE_PICK_SUPERTYPE); return true; case R.id.menuItemDeleteSupertype: _state.setDeletingSupertype(); showDeleteSupertypeConfirmationDialog(); return true; } return false; } private void showDeleteFromBunchConfirmationDialog() { final String message = getString(R.string.deleteFromBunchConfirmationText, _state.getDeleteTarget().text); new AlertDialog.Builder(this) .setMessage(message) .setPositiveButton(R.string.menuItemDelete, this) .setOnCancelListener(dialog -> _state.clearDeleteTarget()) .create().show(); } private void showDeleteAcceptationFromBunchConfirmationDialog() { final String message = getString(R.string.deleteAcceptationFromBunchConfirmationText, _state.getDeleteTarget().text); new AlertDialog.Builder(this) .setMessage(message) .setPositiveButton(R.string.menuItemDelete, this) .setOnCancelListener(dialog -> _state.clearDeleteTarget()) .create().show(); } private void showDeleteConfirmationDialog() { new AlertDialog.Builder(this) .setMessage(R.string.deleteAcceptationConfirmationText) .setPositiveButton(R.string.menuItemDelete, this) .setOnCancelListener(dialog -> _state.clearDeletingAcceptation()) .create().show(); } private void showDeleteSupertypeConfirmationDialog() { new AlertDialog.Builder(this) .setMessage(R.string.deleteSupertypeConfirmationText) .setPositiveButton(R.string.menuItemDelete, this) .setOnCancelListener(dialog -> _state.clearDeletingSupertype()) .create().show(); } @Override public void onClick(DialogInterface dialog, int which) { switch (_state.getIntrinsicState()) { case IntrinsicStates.DELETE_ACCEPTATION: deleteAcceptation(); break; case IntrinsicStates.DELETE_SUPERTYPE: _state.clearDeletingSupertype(); if (!deleteBunchConceptForConcept(DbManager.getInstance().getDatabase(), _concept)) { throw new AssertionError(); } updateAdapter(); showFeedback(getString(R.string.deleteSupertypeFeedback)); invalidateOptionsMenu(); break; case IntrinsicStates.LINKING_CONCEPT: if (_state.getDialogCheckedOption() == 0) { // Sharing concept showFeedback(shareConcept()? "Concept shared" : "Unable to shared concept"); } else { // Duplicate concepts duplicateAcceptationWithThisConcept(); showFeedback("Acceptation linked"); } _state.clearLinkedAcceptation(); updateAdapter(); break; case IntrinsicStates.DELETING_FROM_BUNCH: final DisplayableItem item = _state.getDeleteTarget(); final int bunch = item.id; final String bunchText = item.text; _state.clearDeleteTarget(); if (!removeAcceptationFromBunch(DbManager.getInstance().getDatabase(), _staticAcceptation, bunch)) { throw new AssertionError(); } updateAdapter(); showFeedback(getString(R.string.deleteFromBunchFeedback, bunchText)); break; case IntrinsicStates.DELETING_ACCEPTATION_FROM_BUNCH: final DisplayableItem itemToDelete = _state.getDeleteTarget(); final int accIdToDelete = itemToDelete.id; final String accToDeleteText = itemToDelete.text; _state.clearDeleteTarget(); if (!removeAcceptationFromBunch(DbManager.getInstance().getDatabase(), _concept, accIdToDelete)) { throw new AssertionError(); } updateAdapter(); showFeedback(getString(R.string.deleteAcceptationFromBunchFeedback, accToDeleteText)); break; default: throw new AssertionError("Unable to handle state " + _state.getIntrinsicState()); } } private void deleteAcceptation() { if (!LangbookDatabase.removeAcceptation(DbManager.getInstance().getDatabase(), _staticAcceptation)) { throw new AssertionError(); } showFeedback(getString(R.string.deleteAcceptationFeedback)); finish(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == REQUEST_CODE_LINKED_ACCEPTATION) { final boolean usedConcept = data .getBooleanExtra(AcceptationPickerActivity.ResultKeys.CONCEPT_USED, false); if (!usedConcept) { _state.setLinkedAcceptation(data.getIntExtra(AcceptationPickerActivity.ResultKeys.ACCEPTATION, 0)); showLinkModeSelectorDialog(); } else { updateAdapter(); } } else if (requestCode == REQUEST_CODE_PICK_ACCEPTATION) { final int pickedAcceptation = data.getIntExtra(AcceptationPickerActivity.ResultKeys.ACCEPTATION, 0); final Database db = DbManager.getInstance().getDatabase(); final int message = addAcceptationInBunch(db, _concept, pickedAcceptation)? R.string.includeInBunchOk : R.string.includeInBunchKo; updateAdapter(); showFeedback(getString(message)); } else if (requestCode == REQUEST_CODE_PICK_BUNCH) { final int pickedAcceptation = data.getIntExtra(AcceptationPickerActivity.ResultKeys.ACCEPTATION, 0); final Database db = DbManager.getInstance().getDatabase(); final int pickedBunch = (pickedAcceptation != 0)? conceptFromAcceptation(db, pickedAcceptation) : 0; final int message = addAcceptationInBunch(db, pickedBunch, _staticAcceptation)? R.string.includeInBunchOk : R.string.includeInBunchKo; updateAdapter(); showFeedback(getString(message)); } else if (requestCode == REQUEST_CODE_PICK_SUPERTYPE) { final int pickedAcceptation = data.getIntExtra(AcceptationPickerActivity.ResultKeys.ACCEPTATION, 0); final Database db = DbManager.getInstance().getDatabase(); final int pickedConcept = (pickedAcceptation != 0)? conceptFromAcceptation(db, pickedAcceptation) : 0; insertBunchConcept(db, pickedConcept, _concept); showFeedback(getString(R.string.includeSupertypeOk)); updateAdapter(); invalidateOptionsMenu(); } } } private void showLinkModeSelectorDialog() { new AlertDialog.Builder(this) .setTitle(R.string.linkDialogTitle) .setPositiveButton(R.string.linkDialogButton, this) .setSingleChoiceItems(R.array.linkDialogOptions, 0, this::onLinkDialogChoiceChecked) .setOnCancelListener(dialog -> _state.clearLinkedAcceptation()) .create().show(); } private void onLinkDialogChoiceChecked(DialogInterface dialog, int which) { _state.setDialogCheckedOption(which); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(SavedKeys.STATE, _state); } private int getLinkedConcept() { final AcceptationsTable table = Tables.acceptations; final DbQuery query = new DbQuery.Builder(table) .where(table.getIdColumnIndex(), _state.getLinkedAcceptation()) .select(table.getConceptColumnIndex()); return DbManager.getInstance().selectSingleRow(query).get(0).toInt(); } private ImmutableIntSet getImmutableConcepts() { final AlphabetsTable table = Tables.alphabets; final DbQuery query = new DbQuery.Builder(table) .select(table.getIdColumnIndex(), table.getLanguageColumnIndex()); final ImmutableIntSetBuilder builder = new ImmutableIntSetBuilder(); for (DbResult.Row row : DbManager.getInstance().attach(query)) { builder.add(row.get(0).toInt()); builder.add(row.get(1).toInt()); } return builder.build(); } private static void updateBunchConceptConcepts(int oldConcept, int newConcept) { final BunchConceptsTable table = Tables.bunchConcepts; final Database db = DbManager.getInstance().getDatabase(); DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getBunchColumnIndex(), oldConcept) .put(table.getBunchColumnIndex(), newConcept) .build(); db.update(query); query = new DbUpdateQuery.Builder(table) .where(table.getConceptColumnIndex(), oldConcept) .put(table.getConceptColumnIndex(), newConcept) .build(); db.update(query); } private static void updateBunchAcceptationConcepts(int oldConcept, int newConcept) { final BunchAcceptationsTable table = Tables.bunchAcceptations; DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getBunchColumnIndex(), oldConcept) .put(table.getBunchColumnIndex(), newConcept) .build(); DbManager.getInstance().getDatabase().update(query); } private static void updateQuestionRules(int oldRule, int newRule) { final QuestionFieldSets table = Tables.questionFieldSets; DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getRuleColumnIndex(), oldRule) .put(table.getRuleColumnIndex(), newRule) .build(); DbManager.getInstance().getDatabase().update(query); } private static void updateQuizBunches(int oldBunch, int newBunch) { final QuizDefinitionsTable table = Tables.quizDefinitions; DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getBunchColumnIndex(), oldBunch) .put(table.getBunchColumnIndex(), newBunch) .build(); DbManager.getInstance().getDatabase().update(query); } private static void updateBunchSetBunches(int oldBunch, int newBunch) { final BunchSetsTable table = Tables.bunchSets; DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getBunchColumnIndex(), oldBunch) .put(table.getBunchColumnIndex(), newBunch) .build(); DbManager.getInstance().getDatabase().update(query); } private static void updateAgentRules(int oldRule, int newRule) { final AgentsTable table = Tables.agents; DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getRuleColumnIndex(), oldRule) .put(table.getRuleColumnIndex(), newRule) .build(); DbManager.getInstance().getDatabase().update(query); } private static void updateAgentTargetBunches(int oldBunch, int newBunch) { final AgentsTable table = Tables.agents; DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getTargetBunchColumnIndex(), oldBunch) .put(table.getTargetBunchColumnIndex(), newBunch) .build(); DbManager.getInstance().getDatabase().update(query); } private static void updateAcceptationConcepts(int oldConcept, int newConcept) { final AcceptationsTable table = Tables.acceptations; DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getConceptColumnIndex(), oldConcept) .put(table.getConceptColumnIndex(), newConcept) .build(); DbManager.getInstance().getDatabase().update(query); } private boolean shareConcept() { final int linkedConcept = getLinkedConcept(); final ImmutableIntSet immutableConcepts = getImmutableConcepts(); if (immutableConcepts.contains(linkedConcept)) { return false; } final int oldConcept = _concept; if (oldConcept == 0 || linkedConcept == 0) { throw new AssertionError(); } updateBunchConceptConcepts(oldConcept, linkedConcept); updateBunchAcceptationConcepts(oldConcept, linkedConcept); updateQuestionRules(oldConcept, linkedConcept); updateQuizBunches(oldConcept, linkedConcept); updateBunchSetBunches(oldConcept, linkedConcept); updateAgentRules(oldConcept, linkedConcept); updateAgentTargetBunches(oldConcept, linkedConcept); updateAcceptationConcepts(oldConcept, linkedConcept); return true; } private void duplicateAcceptationWithThisConcept() { final int concept = _concept; if (concept == 0) { throw new AssertionError(); } final int linkedAcceptation = _state.getLinkedAcceptation(); final AcceptationsTable table = Tables.acceptations; final DbQuery query = new DbQuery.Builder(table) .where(table.getIdColumnIndex(), linkedAcceptation) .select(table.getCorrelationArrayColumnIndex()); final Database db = DbManager.getInstance().getDatabase(); final DbResult result = db.select(query); final DbResult.Row row = result.next(); if (result.hasNext()) { throw new AssertionError(); } final int correlationArray = row.get(0).toInt(); final DbInsertQuery insertQuery = new DbInsertQuery.Builder(table) .put(table.getConceptColumnIndex(), _concept) .put(table.getCorrelationArrayColumnIndex(), correlationArray) .build(); final int newAccId = db.insert(insertQuery); final StringQueriesTable strings = Tables.stringQueries; final DbQuery stringsQuery = new DbQuery.Builder(strings) .where(strings.getDynamicAcceptationColumnIndex(), linkedAcceptation) .where(strings.getMainAcceptationColumnIndex(), linkedAcceptation) .select(strings.getStringAlphabetColumnIndex(), strings.getStringColumnIndex(), strings.getMainStringColumnIndex()); final ImmutableIntList.Builder alphabetsBuilder = new ImmutableIntList.Builder(); final ImmutableList.Builder<String> stringsBuilder = new ImmutableList.Builder<>(); final ImmutableList.Builder<String> mainStringsBuilder = new ImmutableList.Builder<>(); for (DbResult.Row r : DbManager.getInstance().attach(stringsQuery)) { alphabetsBuilder.add(r.get(0).toInt()); stringsBuilder.add(r.get(1).toText()); mainStringsBuilder.add(r.get(2).toText()); } final ImmutableIntList alphabets = alphabetsBuilder.build(); final ImmutableList<String> strs = stringsBuilder.build(); final ImmutableList<String> mainStrs = mainStringsBuilder.build(); final int length = alphabets.size(); for (int i = 0; i < length; i++) { final DbInsertQuery iQuery = new DbInsertQuery.Builder(strings) .put(strings.getDynamicAcceptationColumnIndex(), newAccId) .put(strings.getMainAcceptationColumnIndex(), newAccId) .put(strings.getStringAlphabetColumnIndex(), alphabets.valueAt(i)) .put(strings.getStringColumnIndex(), strs.valueAt(i)) .put(strings.getMainStringColumnIndex(), mainStrs.valueAt(i)) .build(); if (db.insert(iQuery) == null) { throw new AssertionError(); } } } private void showFeedback(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } }
app/src/main/java/sword/langbook3/android/AcceptationDetailsActivity.java
package sword.langbook3.android; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ClickableSpan; import android.util.SparseArray; import android.util.SparseIntArray; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import sword.collections.ImmutableIntList; import sword.collections.ImmutableIntSet; import sword.collections.ImmutableIntSetBuilder; import sword.collections.ImmutableList; import sword.langbook3.android.AcceptationDetailsActivityState.IntrinsicStates; import sword.langbook3.android.AcceptationDetailsAdapter.AcceptationNavigableItem; import sword.langbook3.android.AcceptationDetailsAdapter.AgentNavigableItem; import sword.langbook3.android.AcceptationDetailsAdapter.HeaderItem; import sword.langbook3.android.AcceptationDetailsAdapter.NonNavigableItem; import sword.langbook3.android.AcceptationDetailsAdapter.RuleNavigableItem; import sword.langbook3.android.LangbookDbSchema.AcceptationsTable; import sword.langbook3.android.LangbookDbSchema.AgentSetsTable; import sword.langbook3.android.LangbookDbSchema.AgentsTable; import sword.langbook3.android.LangbookDbSchema.AlphabetsTable; import sword.langbook3.android.LangbookDbSchema.BunchAcceptationsTable; import sword.langbook3.android.LangbookDbSchema.BunchConceptsTable; import sword.langbook3.android.LangbookDbSchema.BunchSetsTable; import sword.langbook3.android.LangbookDbSchema.CorrelationArraysTable; import sword.langbook3.android.LangbookDbSchema.CorrelationsTable; import sword.langbook3.android.LangbookDbSchema.LanguagesTable; import sword.langbook3.android.LangbookDbSchema.QuestionFieldSets; import sword.langbook3.android.LangbookDbSchema.QuizDefinitionsTable; import sword.langbook3.android.LangbookDbSchema.RuledAcceptationsTable; import sword.langbook3.android.LangbookDbSchema.StringQueriesTable; import sword.langbook3.android.LangbookDbSchema.SymbolArraysTable; import sword.langbook3.android.LangbookDbSchema.Tables; import sword.langbook3.android.db.Database; import sword.langbook3.android.db.DbExporter; import sword.langbook3.android.db.DbInsertQuery; import sword.langbook3.android.db.DbQuery; import sword.langbook3.android.db.DbResult; import sword.langbook3.android.db.DbUpdateQuery; import static sword.langbook3.android.LangbookDatabase.addAcceptationInBunch; import static sword.langbook3.android.LangbookDatabase.removeAcceptationFromBunch; import static sword.langbook3.android.LangbookDbInserter.insertBunchConcept; import static sword.langbook3.android.LangbookDeleter.deleteBunchConceptForConcept; import static sword.langbook3.android.LangbookReadableDatabase.conceptFromAcceptation; import static sword.langbook3.android.LangbookReadableDatabase.readConceptText; import static sword.langbook3.android.db.DbIdColumn.idColumnName; public final class AcceptationDetailsActivity extends Activity implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, DialogInterface.OnClickListener { private static final int REQUEST_CODE_LINKED_ACCEPTATION = 1; private static final int REQUEST_CODE_PICK_ACCEPTATION = 2; private static final int REQUEST_CODE_PICK_BUNCH = 3; private static final int REQUEST_CODE_PICK_SUPERTYPE = 4; private interface ArgKeys { String STATIC_ACCEPTATION = BundleKeys.STATIC_ACCEPTATION; String DYNAMIC_ACCEPTATION = BundleKeys.DYNAMIC_ACCEPTATION; } private interface SavedKeys { String STATE = "cSt"; } // Specifies the alphabet the user would like to see if possible. // TODO: This should be a shared preference static final int preferredAlphabet = 4; private int _staticAcceptation; private int _concept; private ImmutableIntSet _bunchesWhereIncluded; private AcceptationResult _definition; private AcceptationDetailsActivityState _state; private boolean _shouldShowBunchChildrenQuizMenuOption; private AcceptationDetailsAdapter _listAdapter; public static void open(Context context, int staticAcceptation, int dynamicAcceptation) { Intent intent = new Intent(context, AcceptationDetailsActivity.class); intent.putExtra(ArgKeys.STATIC_ACCEPTATION, staticAcceptation); intent.putExtra(ArgKeys.DYNAMIC_ACCEPTATION, dynamicAcceptation); context.startActivity(intent); } static final class CorrelationHolder { final int id; final SparseArray<String> texts; CorrelationHolder(int id, SparseArray<String> texts) { this.id = id; this.texts = texts; } } private List<CorrelationHolder> readCorrelationArray(SQLiteDatabase db, int acceptation) { final AcceptationsTable acceptations = Tables.acceptations; // J0 final CorrelationArraysTable correlationArrays = Tables.correlationArrays; // J1 final CorrelationsTable correlations = Tables.correlations; // J2 final SymbolArraysTable symbolArrays = Tables.symbolArrays; // J3 Cursor cursor = db.rawQuery( "SELECT" + " J1." + correlationArrays.columns().get(correlationArrays.getArrayPositionColumnIndex()).name() + ",J2." + correlations.columns().get(correlations.getCorrelationIdColumnIndex()).name() + ",J2." + correlations.columns().get(correlations.getAlphabetColumnIndex()).name() + ",J3." + symbolArrays.columns().get(symbolArrays.getStrColumnIndex()).name() + " FROM " + acceptations.name() + " AS J0" + " JOIN " + correlationArrays.name() + " AS J1 ON J0." + acceptations.columns().get(acceptations.getCorrelationArrayColumnIndex()).name() + "=J1." + correlationArrays.columns().get(correlationArrays.getArrayIdColumnIndex()).name() + " JOIN " + correlations.name() + " AS J2 ON J1." + correlationArrays.columns().get(correlationArrays.getCorrelationColumnIndex()).name() + "=J2." + correlations.columns().get(correlations.getCorrelationIdColumnIndex()).name() + " JOIN " + symbolArrays.name() + " AS J3 ON J2." + correlations.columns().get(correlations.getSymbolArrayColumnIndex()).name() + "=J3." + idColumnName + " WHERE J0." + idColumnName + "=?" + " ORDER BY" + " J1." + correlationArrays.columns().get(correlationArrays.getArrayPositionColumnIndex()).name() + ",J2." + correlations.columns().get(correlations.getAlphabetColumnIndex()).name() , new String[] { Integer.toString(acceptation) }); final ArrayList<CorrelationHolder> result = new ArrayList<>(); if (cursor != null) { try { if (cursor.moveToFirst()) { SparseArray<String> corr = new SparseArray<>(); int pos = cursor.getInt(0); int correlationId = cursor.getInt(1); if (pos != result.size()) { throw new AssertionError("Expected position " + result.size() + ", but it was " + pos); } corr.put(cursor.getInt(2), cursor.getString(3)); while(cursor.moveToNext()) { int newPos = cursor.getInt(0); if (newPos != pos) { result.add(new CorrelationHolder(correlationId, corr)); correlationId = cursor.getInt(1); corr = new SparseArray<>(); } pos = newPos; if (newPos != result.size()) { throw new AssertionError("Expected position " + result.size() + ", but it was " + pos); } corr.put(cursor.getInt(2), cursor.getString(3)); } result.add(new CorrelationHolder(correlationId, corr)); } } finally { cursor.close(); } } return result; } private static final class LanguageResult { final int acceptation; final int language; final String text; LanguageResult(int acceptation, int language, String text) { this.acceptation = acceptation; this.language = language; this.text = text; } } private LanguageResult readLanguageFromAlphabet(SQLiteDatabase db, int alphabet) { final AcceptationsTable acceptations = Tables.acceptations; // J0 final AlphabetsTable alphabets = Tables.alphabets; final StringQueriesTable strings = Tables.stringQueries; Cursor cursor = db.rawQuery( "SELECT" + " J1." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + ",J1." + idColumnName + ",J2." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + ",J2." + strings.columns().get(strings.getStringColumnIndex()).name() + " FROM " + alphabets.name() + " AS J0" + " JOIN " + acceptations.name() + " AS J1 ON J0." + alphabets.columns().get(alphabets.getLanguageColumnIndex()).name() + "=J1." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + " JOIN " + strings.name() + " AS J2 ON J1." + idColumnName + "=J2." + strings.columns().get(strings.getDynamicAcceptationColumnIndex()).name() + " WHERE J0." + idColumnName + "=?", new String[] { Integer.toString(alphabet) }); int lang = -1; int langAcc = -1; String text = null; try { cursor.moveToFirst(); lang = cursor.getInt(0); langAcc = cursor.getInt(1); int firstAlphabet = cursor.getInt(2); text = cursor.getString(3); while (firstAlphabet != preferredAlphabet && cursor.moveToNext()) { if (cursor.getInt(2) == preferredAlphabet) { lang = cursor.getInt(0); langAcc = cursor.getInt(1); firstAlphabet = preferredAlphabet; text = cursor.getString(3); } } } finally { cursor.close(); } return new LanguageResult(langAcc, lang, text); } private static final class AcceptationResult { final int acceptation; final String text; AcceptationResult(int acceptation, String text) { this.acceptation = acceptation; this.text = text; } } private AcceptationResult readDefinition(SQLiteDatabase db, int acceptation) { final AcceptationsTable acceptations = Tables.acceptations; final BunchConceptsTable bunchConcepts = Tables.bunchConcepts; final StringQueriesTable strings = Tables.stringQueries; Cursor cursor = db.rawQuery( "SELECT" + " J2." + idColumnName + ",J3." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + ",J3." + strings.columns().get(strings.getStringColumnIndex()).name() + " FROM " + acceptations.name() + " AS J0" + " JOIN " + bunchConcepts.name() + " AS J1 ON J0." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + "=J1." + bunchConcepts.columns().get(bunchConcepts.getConceptColumnIndex()).name() + " JOIN " + acceptations.name() + " AS J2 ON J1." + bunchConcepts.columns().get(bunchConcepts.getBunchColumnIndex()).name() + "=J2." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + " JOIN " + strings.name() + " AS J3 ON J2." + idColumnName + "=J3." + strings.columns().get(strings.getDynamicAcceptationColumnIndex()).name() + " WHERE J0." + idColumnName + "=?", new String[] { Integer.toString(acceptation) }); AcceptationResult result = null; if (cursor != null) { try { if (cursor.moveToFirst()) { int acc = cursor.getInt(0); int firstAlphabet = cursor.getInt(1); String text = cursor.getString(2); while (firstAlphabet != preferredAlphabet && cursor.moveToNext()) { if (cursor.getInt(1) == preferredAlphabet) { acc = cursor.getInt(0); text = cursor.getString(2); break; } } result = new AcceptationResult(acc, text); } } finally { cursor.close(); } } return result; } private AcceptationResult[] readSubTypes(SQLiteDatabase db, int acceptation, int language) { final AcceptationsTable acceptations = Tables.acceptations; final AlphabetsTable alphabets = Tables.alphabets; final BunchConceptsTable bunchConcepts = Tables.bunchConcepts; final StringQueriesTable strings = Tables.stringQueries; Cursor cursor = db.rawQuery( "SELECT" + " J2." + idColumnName + ",J3." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + ",J3." + strings.columns().get(strings.getStringColumnIndex()).name() + " FROM " + acceptations.name() + " AS J0" + " JOIN " + bunchConcepts.name() + " AS J1 ON J0." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + "=J1." + bunchConcepts.columns().get(bunchConcepts.getBunchColumnIndex()).name() + " JOIN " + acceptations.name() + " AS J2 ON J1." + bunchConcepts.columns().get(bunchConcepts.getConceptColumnIndex()).name() + "=J2." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + " JOIN " + strings.name() + " AS J3 ON J2." + idColumnName + "=J3." + strings.columns().get(strings.getDynamicAcceptationColumnIndex()).name() + " JOIN " + alphabets.name() + " AS J4 ON J3." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + "=J4." + idColumnName + " WHERE J0." + idColumnName + "=?" + " AND J4." + alphabets.columns().get(alphabets.getLanguageColumnIndex()).name() + "=?" + " ORDER BY J2." + idColumnName, new String[] { Integer.toString(acceptation), Integer.toString(language) }); if (cursor != null) { try { if (cursor.moveToFirst()) { final ArrayList<AcceptationResult> result = new ArrayList<>(); int acc = cursor.getInt(0); int alphabet = cursor.getInt(1); String text = cursor.getString(2); while (cursor.moveToNext()) { if (cursor.getInt(0) == acc) { if (alphabet != preferredAlphabet && cursor.getInt(1) == preferredAlphabet) { alphabet = preferredAlphabet; text = cursor.getString(2); } } else { result.add(new AcceptationResult(acc, text)); acc = cursor.getInt(0); alphabet = cursor.getInt(1); text = cursor.getString(2); } } result.add(new AcceptationResult(acc, text)); return result.toArray(new AcceptationResult[result.size()]); } } finally { cursor.close(); } } return new AcceptationResult[0]; } private static final class BunchInclusionResult { final int acceptation; final boolean dynamic; final String text; BunchInclusionResult(int acceptation, boolean dynamic, String text) { this.acceptation = acceptation; this.dynamic = dynamic; this.text = text; } } private BunchInclusionResult[] readBunchesWhereIncluded(SQLiteDatabase db, int acceptation) { final AcceptationsTable acceptations = Tables.acceptations; final BunchAcceptationsTable bunchAcceptations = Tables.bunchAcceptations; final StringQueriesTable strings = Tables.stringQueries; final ImmutableIntSetBuilder bunchSetBuilder = new ImmutableIntSetBuilder(); Cursor cursor = db.rawQuery( "SELECT" + " J0." + bunchAcceptations.columns().get(bunchAcceptations.getBunchColumnIndex()).name() + ",J1." + idColumnName + ",J2." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + ",J2." + strings.columns().get(strings.getStringColumnIndex()).name() + ",J0." + bunchAcceptations.columns().get(bunchAcceptations.getAgentSetColumnIndex()).name() + " FROM " + bunchAcceptations.name() + " AS J0" + " JOIN " + acceptations.name() + " AS J1 ON J0." + bunchAcceptations.columns().get(bunchAcceptations.getBunchColumnIndex()).name() + "=J1." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + " JOIN " + strings.name() + " AS J2 ON J1." + idColumnName + "=J2." + strings.columns().get(strings.getDynamicAcceptationColumnIndex()).name() + " WHERE J0." + bunchAcceptations.columns().get(bunchAcceptations.getAcceptationColumnIndex()).name() + "=?", new String[] { Integer.toString(acceptation) }); if (cursor != null) { try { if (cursor.moveToFirst()) { final int nullAgentSet = Tables.agentSets.nullReference(); ArrayList<BunchInclusionResult> result = new ArrayList<>(); int bunch = cursor.getInt(0); int acc = cursor.getInt(1); int firstAlphabet = cursor.getInt(2); String text = cursor.getString(3); int agentSet = cursor.getInt(4); while (cursor.moveToNext()) { if (firstAlphabet != preferredAlphabet && cursor.getInt(2) == preferredAlphabet) { acc = cursor.getInt(1); text = cursor.getString(3); firstAlphabet = preferredAlphabet; } if (bunch != cursor.getInt(0)) { bunchSetBuilder.add(bunch); result.add(new BunchInclusionResult(acc, agentSet != nullAgentSet, text)); bunch = cursor.getInt(0); agentSet = cursor.getInt(4); acc = cursor.getInt(1); firstAlphabet = cursor.getInt(2); text = cursor.getString(3); } } bunchSetBuilder.add(bunch); result.add(new BunchInclusionResult(acc, agentSet != nullAgentSet, text)); return result.toArray(new BunchInclusionResult[result.size()]); } } finally { cursor.close(); } } _bunchesWhereIncluded = bunchSetBuilder.build(); return new BunchInclusionResult[0]; } private static final class BunchChildResult { final int acceptation; final boolean dynamic; final String text; BunchChildResult(int acceptation, boolean dynamic, String text) { this.acceptation = acceptation; this.dynamic = dynamic; this.text = text; } } private BunchChildResult[] readBunchChildren(SQLiteDatabase db, int acceptation) { final AcceptationsTable acceptations = Tables.acceptations; final BunchAcceptationsTable bunchAcceptations = Tables.bunchAcceptations; final StringQueriesTable strings = Tables.stringQueries; Cursor cursor = db.rawQuery( "SELECT" + " J1." + bunchAcceptations.columns().get(bunchAcceptations.getAcceptationColumnIndex()).name() + ",J2." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + ",J2." + strings.columns().get(strings.getStringColumnIndex()).name() + ",J1." + bunchAcceptations.columns().get(bunchAcceptations.getAgentSetColumnIndex()).name() + " FROM " + acceptations.name() + " AS J0" + " JOIN " + bunchAcceptations.name() + " AS J1 ON J0." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + "=J1." + bunchAcceptations.columns().get(bunchAcceptations.getBunchColumnIndex()).name() + " JOIN " + strings.name() + " AS J2 ON J1." + bunchAcceptations.columns().get(bunchAcceptations.getAcceptationColumnIndex()).name() + "=J2." + strings.columns().get(strings.getDynamicAcceptationColumnIndex()).name() + " WHERE J0." + idColumnName + "=?" + " ORDER BY J1." + bunchAcceptations.columns().get(bunchAcceptations.getAcceptationColumnIndex()).name(), new String[] { Integer.toString(acceptation) }); if (cursor != null) { try { if (cursor.moveToFirst()) { final int nullAgentSet = Tables.agentSets.nullReference(); ArrayList<BunchChildResult> result = new ArrayList<>(); int acc = cursor.getInt(0); int alphabet = cursor.getInt(1); String text = cursor.getString(2); int agentSet = cursor.getInt(3); while (cursor.moveToNext()) { if (acc == cursor.getInt(0)) { if (alphabet != preferredAlphabet && cursor.getInt(2) == preferredAlphabet) { alphabet = preferredAlphabet; text = cursor.getString(2); } } else { result.add(new BunchChildResult(acc, agentSet != nullAgentSet, text)); acc = cursor.getInt(0); alphabet = cursor.getInt(1); text = cursor.getString(2); agentSet = cursor.getInt(3); } } result.add(new BunchChildResult(acc, agentSet != nullAgentSet, text)); return result.toArray(new BunchChildResult[result.size()]); } } finally { cursor.close(); } } return new BunchChildResult[0]; } private static final class SynonymTranslationResult { final int acceptation; final int language; final String text; SynonymTranslationResult(int acceptation, int language, String text) { this.acceptation = acceptation; this.language = language; this.text = text; } } private ImmutableList<SynonymTranslationResult> readSynonymsAndTranslations(DbExporter.Database db, int acceptation) { final AcceptationsTable acceptations = Tables.acceptations; final AlphabetsTable alphabets = Tables.alphabets; final StringQueriesTable strings = Tables.stringQueries; final LanguagesTable languages = Tables.languages; final int accOffset = acceptations.columns().size(); final int stringsOffset = accOffset * 2; final int alphabetsOffset = stringsOffset + strings.columns().size(); final int languagesOffset = alphabetsOffset + alphabets.columns().size(); final DbQuery query = new DbQuery.Builder(acceptations) .join(acceptations, acceptations.getConceptColumnIndex(), acceptations.getConceptColumnIndex()) .join(strings, acceptations.columns().size() + acceptations.getIdColumnIndex(), strings.getDynamicAcceptationColumnIndex()) .join(alphabets, stringsOffset + strings.getStringAlphabetColumnIndex(), alphabets.getIdColumnIndex()) .join(languages, alphabetsOffset + alphabets.getLanguageColumnIndex(), languages.getIdColumnIndex()) .where(acceptations.getIdColumnIndex(), acceptation) .whereColumnValueMatch(alphabetsOffset + alphabets.getIdColumnIndex(), languagesOffset + languages.getMainAlphabetColumnIndex()) .select(accOffset + acceptations.getIdColumnIndex(), languagesOffset + languages.getIdColumnIndex(), stringsOffset + strings.getStringColumnIndex()); final DbResult result = db.select(query); final ImmutableList.Builder<SynonymTranslationResult> builder = new ImmutableList.Builder<>(result.getRemainingRows()); try { while (result.hasNext()) { final DbResult.Row row = result.next(); final int accId = row.get(0).toInt(); if (accId != acceptation) { builder.add(new SynonymTranslationResult(accId, row.get(1).toInt(), row.get(2).toText())); } } } finally { result.close(); } return builder.build(); } private static final class MorphologyResult { final int agent; final int dynamicAcceptation; final int rule; final String ruleText; final String text; MorphologyResult(int agent, int dynamicAcceptation, int rule, String ruleText, String text) { this.agent = agent; this.dynamicAcceptation = dynamicAcceptation; this.rule = rule; this.ruleText = ruleText; this.text = text; } } private MorphologyResult[] readMorphologies(SQLiteDatabase db, int acceptation) { final AcceptationsTable acceptations = Tables.acceptations; final AgentsTable agents = Tables.agents; final StringQueriesTable strings = Tables.stringQueries; final RuledAcceptationsTable ruledAcceptations = Tables.ruledAcceptations; Cursor cursor = db.rawQuery( "SELECT" + " J0." + idColumnName + ",J3." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + ",J1." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + ",J1." + strings.columns().get(strings.getStringColumnIndex()).name() + ",J4." + strings.columns().get(strings.getStringAlphabetColumnIndex()).name() + ",J4." + strings.columns().get(strings.getStringColumnIndex()).name() + ",J2." + idColumnName + " FROM " + ruledAcceptations.name() + " AS J0" + " JOIN " + strings.name() + " AS J1 ON J0." + idColumnName + "=J1." + strings.columns().get(strings.getDynamicAcceptationColumnIndex()).name() + " JOIN " + agents.name() + " AS J2 ON J0." + ruledAcceptations.columns().get(ruledAcceptations.getAgentColumnIndex()).name() + "=J2." + idColumnName + " JOIN " + acceptations.name() + " AS J3 ON J2." + agents.columns().get(agents.getRuleColumnIndex()).name() + "=J3." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + " JOIN " + strings.name() + " AS J4 ON J3." + idColumnName + "=J4." + strings.columns().get(strings.getDynamicAcceptationColumnIndex()).name() + " WHERE J0." + ruledAcceptations.columns().get(ruledAcceptations.getAcceptationColumnIndex()).name() + "=?" + " AND J1." + strings.columns().get(strings.getMainAcceptationColumnIndex()).name() + "=?" + " ORDER BY J0." + idColumnName, new String[] { Integer.toString(acceptation) , Integer.toString(acceptation)}); if (cursor != null) { try { if (cursor.moveToFirst()) { ArrayList<MorphologyResult> result = new ArrayList<>(); int acc = cursor.getInt(0); int rule = cursor.getInt(1); int alphabet = cursor.getInt(2); String text = cursor.getString(3); int ruleAlphabet = cursor.getInt(4); String ruleText = cursor.getString(5); int agent = cursor.getInt(6); while (cursor.moveToNext()) { if (cursor.getInt(0) == acc) { if (alphabet != preferredAlphabet && cursor.getInt(2) == preferredAlphabet) { alphabet = preferredAlphabet; text = cursor.getString(3); } if (ruleAlphabet != preferredAlphabet && cursor.getInt(4) == preferredAlphabet) { ruleAlphabet = preferredAlphabet; ruleText = cursor.getString(5); } } else { result.add(new MorphologyResult(agent, acc, rule, ruleText, text)); acc = cursor.getInt(0); rule = cursor.getInt(1); alphabet = cursor.getInt(2); text = cursor.getString(3); ruleAlphabet = cursor.getInt(4); ruleText = cursor.getString(5); agent = cursor.getInt(6); } } result.add(new MorphologyResult(agent, acc, rule, ruleText, text)); return result.toArray(new MorphologyResult[result.size()]); } } finally { cursor.close(); } } return new MorphologyResult[0]; } private static class InvolvedAgentResult { interface Flags { int target = 1; int source = 2; int diff = 4; int rule = 8; int processed = 16; } final int agentId; final int flags; InvolvedAgentResult(int agentId, int flags) { this.agentId = agentId; this.flags = flags; } } private int[] readAgentsWhereAccIsTarget(SQLiteDatabase db, int staticAcceptation) { final AcceptationsTable acceptations = Tables.acceptations; final AgentsTable agents = Tables.agents; final Cursor cursor = db.rawQuery(" SELECT J1." + idColumnName + " FROM " + acceptations.name() + " AS J0" + " JOIN " + agents.name() + " AS J1 ON J0." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + "=J1." + agents.columns().get(agents.getTargetBunchColumnIndex()).name() + " WHERE J0." + idColumnName + "=?", new String[] { Integer.toString(staticAcceptation)}); if (cursor != null) { try { if (cursor.moveToFirst()) { int[] result = new int[cursor.getCount()]; int index = 0; do { result[index++] = cursor.getInt(0); } while (cursor.moveToNext()); return result; } } finally { cursor.close(); } } return new int[0]; } private int[] readAgentsWhereAccIsSource(SQLiteDatabase db, int staticAcceptation) { final AcceptationsTable acceptations = Tables.acceptations; final AgentsTable agents = Tables.agents; final BunchSetsTable bunchSets = Tables.bunchSets; final Cursor cursor = db.rawQuery(" SELECT J2." + idColumnName + " FROM " + acceptations.name() + " AS J0" + " JOIN " + bunchSets.name() + " AS J1 ON J0." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + "=J1." + bunchSets.columns().get(bunchSets.getBunchColumnIndex()).name() + " JOIN " + agents.name() + " AS J2 ON J1." + bunchSets.columns().get(bunchSets.getSetIdColumnIndex()).name() + "=J2." + agents.columns().get(agents.getSourceBunchSetColumnIndex()).name() + " WHERE J0." + idColumnName + "=?", new String[] { Integer.toString(staticAcceptation)}); if (cursor != null) { try { if (cursor.moveToFirst()) { int[] result = new int[cursor.getCount()]; int index = 0; do { result[index++] = cursor.getInt(0); } while (cursor.moveToNext()); return result; } } finally { cursor.close(); } } return new int[0]; } private int[] readAgentsWhereAccIsRule(SQLiteDatabase db, int staticAcceptation) { final AcceptationsTable acceptations = Tables.acceptations; final AgentsTable agents = Tables.agents; final Cursor cursor = db.rawQuery(" SELECT J1." + idColumnName + " FROM " + acceptations.name() + " AS J0" + " JOIN " + agents.name() + " AS J1 ON J0." + acceptations.columns().get(acceptations.getConceptColumnIndex()).name() + "=J1." + agents.columns().get(agents.getRuleColumnIndex()).name() + " WHERE J0." + idColumnName + "=?", new String[] { Integer.toString(staticAcceptation)}); if (cursor != null) { try { if (cursor.moveToFirst()) { int[] result = new int[cursor.getCount()]; int index = 0; do { result[index++] = cursor.getInt(0); } while (cursor.moveToNext()); return result; } } finally { cursor.close(); } } return new int[0]; } private int[] readAgentsWhereAccIsProcessed(SQLiteDatabase db, int staticAcceptation) { final AgentsTable agents = Tables.agents; final BunchAcceptationsTable bunchAcceptations = Tables.bunchAcceptations; final AgentSetsTable agentSets = Tables.agentSets; final Cursor cursor = db.rawQuery(" SELECT J1." + agentSets.columns().get(agentSets.getAgentColumnIndex()).name() + " FROM " + bunchAcceptations.name() + " AS J0" + " JOIN " + agentSets.name() + " AS J1 ON J0." + bunchAcceptations.columns().get(bunchAcceptations.getAgentSetColumnIndex()).name() + "=J1." + agentSets.columns().get(agentSets.getSetIdColumnIndex()).name() + " WHERE J0." + bunchAcceptations.columns().get(bunchAcceptations.getAcceptationColumnIndex()).name() + "=?", new String[] { Integer.toString(staticAcceptation)}); if (cursor != null) { try { if (cursor.moveToFirst()) { ArrayList<Integer> result = new ArrayList<>(); do { final int id = cursor.getInt(0); if (id != agents.nullReference()) { result.add(id); } } while (cursor.moveToNext()); int[] intResult = new int[result.size()]; int index = 0; for (int value : result) { intResult[index++] = value; } return intResult; } } finally { cursor.close(); } } return new int[0]; } private InvolvedAgentResult[] readInvolvedAgents(SQLiteDatabase db, int staticAcceptation) { final SparseIntArray flags = new SparseIntArray(); for (int agentId : readAgentsWhereAccIsTarget(db, staticAcceptation)) { flags.put(agentId, flags.get(agentId) | InvolvedAgentResult.Flags.target); } for (int agentId : readAgentsWhereAccIsSource(db, staticAcceptation)) { flags.put(agentId, flags.get(agentId) | InvolvedAgentResult.Flags.source); } // TODO: Diff not implemented as right now it is impossible for (int agentId : readAgentsWhereAccIsRule(db, staticAcceptation)) { flags.put(agentId, flags.get(agentId) | InvolvedAgentResult.Flags.rule); } for (int agentId : readAgentsWhereAccIsProcessed(db, staticAcceptation)) { flags.put(agentId, flags.get(agentId) | InvolvedAgentResult.Flags.processed); } final int count = flags.size(); final InvolvedAgentResult[] result = new InvolvedAgentResult[count]; for (int i = 0; i < count; i++) { result[i] = new InvolvedAgentResult(flags.keyAt(i), flags.valueAt(i)); } return result; } private class CorrelationSpan extends ClickableSpan { final int id; final int start; final int end; CorrelationSpan(int id, int start, int end) { if (start < 0 || end < start) { throw new IllegalArgumentException(); } this.id = id; this.start = start; this.end = end; } @Override public void onClick(View view) { CorrelationDetailsActivity.open(AcceptationDetailsActivity.this, id); } } static void composeCorrelation(SparseArray<String> correlation, StringBuilder sb) { final int correlationSize = correlation.size(); for (int i = 0; i < correlationSize; i++) { if (i != 0) { sb.append('/'); } sb.append(correlation.valueAt(i)); } } private AcceptationDetailsAdapter.Item[] getAdapterItems(int staticAcceptation) { SQLiteDatabase db = DbManager.getInstance().getReadableDatabase(); final ArrayList<AcceptationDetailsAdapter.Item> result = new ArrayList<>(); result.add(new HeaderItem("Displaying details for acceptation " + staticAcceptation)); final StringBuilder sb = new StringBuilder("Correlation: "); List<CorrelationHolder> correlationArray = readCorrelationArray(db, staticAcceptation); List<CorrelationSpan> correlationSpans = new ArrayList<>(); for (int i = 0; i < correlationArray.size(); i++) { if (i != 0) { sb.append(" - "); } final CorrelationHolder holder = correlationArray.get(i); final SparseArray<String> correlation = holder.texts; final int correlationSize = correlation.size(); int startIndex = -1; if (correlationSize > 1) { startIndex = sb.length(); } composeCorrelation(correlation, sb); if (startIndex >= 0) { correlationSpans.add(new CorrelationSpan(holder.id, startIndex, sb.length())); } } SpannableString spannableCorrelations = new SpannableString(sb.toString()); for (CorrelationSpan span : correlationSpans) { spannableCorrelations.setSpan(span, span.start, span.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } result.add(new NonNavigableItem(spannableCorrelations)); final LanguageResult languageResult = readLanguageFromAlphabet(db, correlationArray.get(0).texts.keyAt(0)); result.add(new NonNavigableItem("Language: " + languageResult.text)); final SparseArray<String> languageStrs = new SparseArray<>(); languageStrs.put(languageResult.language, languageResult.text); _definition = readDefinition(db, staticAcceptation); if (_definition != null) { result.add(new AcceptationNavigableItem(_definition.acceptation, "Type of: " + _definition.text, false)); } boolean subTypeFound = false; for (AcceptationResult subType : readSubTypes(db, staticAcceptation, languageResult.language)) { if (!subTypeFound) { result.add(new HeaderItem("Subtypes")); subTypeFound = true; } result.add(new AcceptationNavigableItem(subType.acceptation, subType.text, false)); } final ImmutableList<SynonymTranslationResult> synonymTranslationResults = readSynonymsAndTranslations(DbManager.getInstance().getDatabase(), staticAcceptation); boolean synonymFound = false; for (SynonymTranslationResult r : synonymTranslationResults) { if (r.language == languageResult.language) { if (!synonymFound) { result.add(new HeaderItem("Synonyms")); synonymFound = true; } result.add(new AcceptationNavigableItem(r.acceptation, r.text, false)); } } boolean translationFound = false; for (SynonymTranslationResult r : synonymTranslationResults) { final int language = r.language; if (language != languageResult.language) { if (!translationFound) { result.add(new HeaderItem("Translations")); translationFound = true; } String langStr = languageStrs.get(language); if (langStr == null) { langStr = readConceptText(DbManager.getInstance().getDatabase(), language, preferredAlphabet); languageStrs.put(language, langStr); } result.add(new AcceptationNavigableItem(r.acceptation, "" + langStr + " -> " + r.text, false)); } } boolean parentBunchFound = false; for (BunchInclusionResult r : readBunchesWhereIncluded(db, staticAcceptation)) { if (!parentBunchFound) { result.add(new HeaderItem("Bunches where included")); parentBunchFound = true; } result.add(new AcceptationNavigableItem(AcceptationDetailsAdapter.ItemTypes.BUNCH_WHERE_INCLUDED, r.acceptation, r.text, r.dynamic)); } boolean morphologyFound = false; MorphologyResult[] morphologyResults = readMorphologies(db, staticAcceptation); for (MorphologyResult r : morphologyResults) { if (!morphologyFound) { result.add(new HeaderItem("Morphologies")); morphologyFound = true; } result.add(new RuleNavigableItem(r.dynamicAcceptation, r.ruleText + " -> " + r.text)); } boolean bunchChildFound = false; for (BunchChildResult r : readBunchChildren(db, staticAcceptation)) { if (!bunchChildFound) { result.add(new HeaderItem("Acceptations included in this bunch")); bunchChildFound = true; _shouldShowBunchChildrenQuizMenuOption = true; } result.add(new AcceptationNavigableItem(AcceptationDetailsAdapter.ItemTypes.ACCEPTATION_INCLUDED, r.acceptation, r.text, r.dynamic)); } boolean agentFound = false; for (InvolvedAgentResult r : readInvolvedAgents(db, staticAcceptation)) { if (!agentFound) { result.add(new HeaderItem("Involved agents")); agentFound = true; } final StringBuilder s = new StringBuilder("Agent #"); s.append(r.agentId).append(" ("); s.append(((r.flags & InvolvedAgentResult.Flags.target) != 0)? 'T' : '-'); s.append(((r.flags & InvolvedAgentResult.Flags.source) != 0)? 'S' : '-'); s.append(((r.flags & InvolvedAgentResult.Flags.diff) != 0)? 'D' : '-'); s.append(((r.flags & InvolvedAgentResult.Flags.rule) != 0)? 'R' : '-'); s.append(((r.flags & InvolvedAgentResult.Flags.processed) != 0)? 'P' : '-'); s.append(')'); result.add(new AgentNavigableItem(r.agentId, s.toString())); } for (MorphologyResult r : morphologyResults) { if (!agentFound) { result.add(new HeaderItem("Involved agents")); agentFound = true; } final StringBuilder s = new StringBuilder("Agent #"); s.append(r.agent).append(" (").append(r.ruleText).append(')'); result.add(new AgentNavigableItem(r.agent, s.toString())); } return result.toArray(new AcceptationDetailsAdapter.Item[result.size()]); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.acceptation_details_activity); if (!getIntent().hasExtra(ArgKeys.STATIC_ACCEPTATION)) { throw new IllegalArgumentException("staticAcceptation not provided"); } if (savedInstanceState != null) { _state = savedInstanceState.getParcelable(SavedKeys.STATE); } if (_state == null) { _state = new AcceptationDetailsActivityState(); } _staticAcceptation = getIntent().getIntExtra(ArgKeys.STATIC_ACCEPTATION, 0); _concept = conceptFromAcceptation(DbManager.getInstance().getDatabase(), _staticAcceptation); if (_concept != 0) { _listAdapter = new AcceptationDetailsAdapter(getAdapterItems(_staticAcceptation)); ListView listView = findViewById(R.id.listView); listView.setAdapter(_listAdapter); listView.setOnItemClickListener(this); listView.setOnItemLongClickListener(this); switch (_state.getIntrinsicState()) { case IntrinsicStates.DELETE_ACCEPTATION: showDeleteConfirmationDialog(); break; case IntrinsicStates.DELETE_SUPERTYPE: showDeleteSupertypeConfirmationDialog(); break; case IntrinsicStates.DELETING_FROM_BUNCH: showDeleteFromBunchConfirmationDialog(); break; case IntrinsicStates.DELETING_ACCEPTATION_FROM_BUNCH: showDeleteAcceptationFromBunchConfirmationDialog(); break; case IntrinsicStates.LINKING_CONCEPT: showLinkModeSelectorDialog(); break; } } else { finish(); } } @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { _listAdapter.getItem(position).navigate(this); } @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { // For now, as the only valuable action per item is 'delete', no // contextual menu is displayed and confirmation dialog is prompted directly. // // This routine may be valuable while there is only one enabled item. // For multiple, the action mode for the list view should be enabled // instead to apply the same action to multiple items at the same time. final AcceptationDetailsAdapter.Item item = _listAdapter.getItem(position); if (item.getItemType() == AcceptationDetailsAdapter.ItemTypes.BUNCH_WHERE_INCLUDED) { AcceptationNavigableItem it = (AcceptationNavigableItem) item; if (!it.isDynamic()) { final int bunch = conceptFromAcceptation(DbManager.getInstance().getDatabase(), it.getId()); _state.setDeleteBunchTarget(new DisplayableItem(bunch, it.getText().toString())); showDeleteFromBunchConfirmationDialog(); } return true; } else if (item.getItemType() == AcceptationDetailsAdapter.ItemTypes.ACCEPTATION_INCLUDED) { AcceptationNavigableItem it = (AcceptationNavigableItem) item; if (!it.isDynamic()) { _state.setDeleteAcceptationFromBunch(new DisplayableItem(it.getId(), it.getText().toString())); showDeleteAcceptationFromBunchConfirmationDialog(); } return true; } return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { final MenuInflater inflater = new MenuInflater(this); if (_shouldShowBunchChildrenQuizMenuOption) { inflater.inflate(R.menu.acceptation_details_activity_bunch_children_quiz, menu); } inflater.inflate(R.menu.acceptation_details_activity_link_options, menu); if (_definition == null) { inflater.inflate(R.menu.acceptation_details_activity_include_supertype, menu); } else { inflater.inflate(R.menu.acceptation_details_activity_delete_supertype, menu); } inflater.inflate(R.menu.acceptation_details_activity_delete_acceptation, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menuItemBunchChildrenQuiz: QuizSelectorActivity.open(this, _concept); return true; case R.id.menuItemLinkConcept: AcceptationPickerActivity.open(this, REQUEST_CODE_LINKED_ACCEPTATION, _concept); return true; case R.id.menuItemIncludeAcceptation: AcceptationPickerActivity.open(this, REQUEST_CODE_PICK_ACCEPTATION); return true; case R.id.menuItemIncludeInBunch: AcceptationPickerActivity.open(this, REQUEST_CODE_PICK_BUNCH); return true; case R.id.menuItemDeleteAcceptation: _state.setDeletingAcceptation(); showDeleteConfirmationDialog(); return true; case R.id.menuItemIncludeSupertype: AcceptationPickerActivity.open(this, REQUEST_CODE_PICK_SUPERTYPE); return true; case R.id.menuItemDeleteSupertype: _state.setDeletingSupertype(); showDeleteSupertypeConfirmationDialog(); return true; } return false; } private void showDeleteFromBunchConfirmationDialog() { final String message = getString(R.string.deleteFromBunchConfirmationText, _state.getDeleteTarget().text); new AlertDialog.Builder(this) .setMessage(message) .setPositiveButton(R.string.menuItemDelete, this) .setOnCancelListener(dialog -> _state.clearDeleteTarget()) .create().show(); } private void showDeleteAcceptationFromBunchConfirmationDialog() { final String message = getString(R.string.deleteAcceptationFromBunchConfirmationText, _state.getDeleteTarget().text); new AlertDialog.Builder(this) .setMessage(message) .setPositiveButton(R.string.menuItemDelete, this) .setOnCancelListener(dialog -> _state.clearDeleteTarget()) .create().show(); } private void showDeleteConfirmationDialog() { new AlertDialog.Builder(this) .setMessage(R.string.deleteAcceptationConfirmationText) .setPositiveButton(R.string.menuItemDelete, this) .setOnCancelListener(dialog -> _state.clearDeletingAcceptation()) .create().show(); } private void showDeleteSupertypeConfirmationDialog() { new AlertDialog.Builder(this) .setMessage(R.string.deleteSupertypeConfirmationText) .setPositiveButton(R.string.menuItemDelete, this) .setOnCancelListener(dialog -> _state.clearDeletingSupertype()) .create().show(); } @Override public void onClick(DialogInterface dialog, int which) { switch (_state.getIntrinsicState()) { case IntrinsicStates.DELETE_ACCEPTATION: deleteAcceptation(); break; case IntrinsicStates.DELETE_SUPERTYPE: _state.clearDeletingSupertype(); if (!deleteBunchConceptForConcept(DbManager.getInstance().getDatabase(), _concept)) { throw new AssertionError(); } showFeedback(getString(R.string.deleteSupertypeFeedback)); break; case IntrinsicStates.LINKING_CONCEPT: if (_state.getDialogCheckedOption() == 0) { // Sharing concept showFeedback(shareConcept()? "Concept shared" : "Unable to shared concept"); } else { // Duplicate concepts duplicateAcceptationWithThisConcept(); showFeedback("Acceptation linked"); } _state.clearLinkedAcceptation(); break; case IntrinsicStates.DELETING_FROM_BUNCH: final DisplayableItem item = _state.getDeleteTarget(); final int bunch = item.id; final String bunchText = item.text; _state.clearDeleteTarget(); if (!removeAcceptationFromBunch(DbManager.getInstance().getDatabase(), _staticAcceptation, bunch)) { throw new AssertionError(); } showFeedback(getString(R.string.deleteFromBunchFeedback, bunchText)); break; case IntrinsicStates.DELETING_ACCEPTATION_FROM_BUNCH: final DisplayableItem itemToDelete = _state.getDeleteTarget(); final int accIdToDelete = itemToDelete.id; final String accToDeleteText = itemToDelete.text; _state.clearDeleteTarget(); if (!removeAcceptationFromBunch(DbManager.getInstance().getDatabase(), _concept, accIdToDelete)) { throw new AssertionError(); } showFeedback(getString(R.string.deleteAcceptationFromBunchFeedback, accToDeleteText)); break; default: throw new AssertionError("Unable to handle state " + _state.getIntrinsicState()); } } private void deleteAcceptation() { if (!LangbookDatabase.removeAcceptation(DbManager.getInstance().getDatabase(), _staticAcceptation)) { throw new AssertionError(); } showFeedback(getString(R.string.deleteAcceptationFeedback)); finish(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == REQUEST_CODE_LINKED_ACCEPTATION) { final boolean usedConcept = data .getBooleanExtra(AcceptationPickerActivity.ResultKeys.CONCEPT_USED, false); if (!usedConcept) { _state.setLinkedAcceptation(data.getIntExtra(AcceptationPickerActivity.ResultKeys.ACCEPTATION, 0)); showLinkModeSelectorDialog(); } } else if (requestCode == REQUEST_CODE_PICK_ACCEPTATION) { final int pickedAcceptation = data.getIntExtra(AcceptationPickerActivity.ResultKeys.ACCEPTATION, 0); final Database db = DbManager.getInstance().getDatabase(); final int message = addAcceptationInBunch(db, _concept, pickedAcceptation)? R.string.includeInBunchOk : R.string.includeInBunchKo; showFeedback(getString(message)); } else if (requestCode == REQUEST_CODE_PICK_BUNCH) { final int pickedAcceptation = data.getIntExtra(AcceptationPickerActivity.ResultKeys.ACCEPTATION, 0); final Database db = DbManager.getInstance().getDatabase(); final int pickedBunch = (pickedAcceptation != 0)? conceptFromAcceptation(db, pickedAcceptation) : 0; final int message = addAcceptationInBunch(db, pickedBunch, _staticAcceptation)? R.string.includeInBunchOk : R.string.includeInBunchKo; showFeedback(getString(message)); } else if (requestCode == REQUEST_CODE_PICK_SUPERTYPE) { final int pickedAcceptation = data.getIntExtra(AcceptationPickerActivity.ResultKeys.ACCEPTATION, 0); final Database db = DbManager.getInstance().getDatabase(); final int pickedConcept = (pickedAcceptation != 0)? conceptFromAcceptation(db, pickedAcceptation) : 0; insertBunchConcept(db, pickedConcept, _concept); showFeedback(getString(R.string.includeSupertypeOk)); } } } private void showLinkModeSelectorDialog() { new AlertDialog.Builder(this) .setTitle(R.string.linkDialogTitle) .setPositiveButton(R.string.linkDialogButton, this) .setSingleChoiceItems(R.array.linkDialogOptions, 0, this::onLinkDialogChoiceChecked) .setOnCancelListener(dialog -> _state.clearLinkedAcceptation()) .create().show(); } private void onLinkDialogChoiceChecked(DialogInterface dialog, int which) { _state.setDialogCheckedOption(which); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(SavedKeys.STATE, _state); } private int getLinkedConcept() { final AcceptationsTable table = Tables.acceptations; final DbQuery query = new DbQuery.Builder(table) .where(table.getIdColumnIndex(), _state.getLinkedAcceptation()) .select(table.getConceptColumnIndex()); return DbManager.getInstance().selectSingleRow(query).get(0).toInt(); } private ImmutableIntSet getImmutableConcepts() { final AlphabetsTable table = Tables.alphabets; final DbQuery query = new DbQuery.Builder(table) .select(table.getIdColumnIndex(), table.getLanguageColumnIndex()); final ImmutableIntSetBuilder builder = new ImmutableIntSetBuilder(); for (DbResult.Row row : DbManager.getInstance().attach(query)) { builder.add(row.get(0).toInt()); builder.add(row.get(1).toInt()); } return builder.build(); } private static void updateBunchConceptConcepts(int oldConcept, int newConcept) { final BunchConceptsTable table = Tables.bunchConcepts; final Database db = DbManager.getInstance().getDatabase(); DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getBunchColumnIndex(), oldConcept) .put(table.getBunchColumnIndex(), newConcept) .build(); db.update(query); query = new DbUpdateQuery.Builder(table) .where(table.getConceptColumnIndex(), oldConcept) .put(table.getConceptColumnIndex(), newConcept) .build(); db.update(query); } private static void updateBunchAcceptationConcepts(int oldConcept, int newConcept) { final BunchAcceptationsTable table = Tables.bunchAcceptations; DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getBunchColumnIndex(), oldConcept) .put(table.getBunchColumnIndex(), newConcept) .build(); DbManager.getInstance().getDatabase().update(query); } private static void updateQuestionRules(int oldRule, int newRule) { final QuestionFieldSets table = Tables.questionFieldSets; DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getRuleColumnIndex(), oldRule) .put(table.getRuleColumnIndex(), newRule) .build(); DbManager.getInstance().getDatabase().update(query); } private static void updateQuizBunches(int oldBunch, int newBunch) { final QuizDefinitionsTable table = Tables.quizDefinitions; DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getBunchColumnIndex(), oldBunch) .put(table.getBunchColumnIndex(), newBunch) .build(); DbManager.getInstance().getDatabase().update(query); } private static void updateBunchSetBunches(int oldBunch, int newBunch) { final BunchSetsTable table = Tables.bunchSets; DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getBunchColumnIndex(), oldBunch) .put(table.getBunchColumnIndex(), newBunch) .build(); DbManager.getInstance().getDatabase().update(query); } private static void updateAgentRules(int oldRule, int newRule) { final AgentsTable table = Tables.agents; DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getRuleColumnIndex(), oldRule) .put(table.getRuleColumnIndex(), newRule) .build(); DbManager.getInstance().getDatabase().update(query); } private static void updateAgentTargetBunches(int oldBunch, int newBunch) { final AgentsTable table = Tables.agents; DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getTargetBunchColumnIndex(), oldBunch) .put(table.getTargetBunchColumnIndex(), newBunch) .build(); DbManager.getInstance().getDatabase().update(query); } private static void updateAcceptationConcepts(int oldConcept, int newConcept) { final AcceptationsTable table = Tables.acceptations; DbUpdateQuery query = new DbUpdateQuery.Builder(table) .where(table.getConceptColumnIndex(), oldConcept) .put(table.getConceptColumnIndex(), newConcept) .build(); DbManager.getInstance().getDatabase().update(query); } private boolean shareConcept() { final int linkedConcept = getLinkedConcept(); final ImmutableIntSet immutableConcepts = getImmutableConcepts(); if (immutableConcepts.contains(linkedConcept)) { return false; } final int oldConcept = _concept; if (oldConcept == 0 || linkedConcept == 0) { throw new AssertionError(); } updateBunchConceptConcepts(oldConcept, linkedConcept); updateBunchAcceptationConcepts(oldConcept, linkedConcept); updateQuestionRules(oldConcept, linkedConcept); updateQuizBunches(oldConcept, linkedConcept); updateBunchSetBunches(oldConcept, linkedConcept); updateAgentRules(oldConcept, linkedConcept); updateAgentTargetBunches(oldConcept, linkedConcept); updateAcceptationConcepts(oldConcept, linkedConcept); return true; } private void duplicateAcceptationWithThisConcept() { final int concept = _concept; if (concept == 0) { throw new AssertionError(); } final int linkedAcceptation = _state.getLinkedAcceptation(); final AcceptationsTable table = Tables.acceptations; final DbQuery query = new DbQuery.Builder(table) .where(table.getIdColumnIndex(), linkedAcceptation) .select(table.getCorrelationArrayColumnIndex()); final Database db = DbManager.getInstance().getDatabase(); final DbResult result = db.select(query); final DbResult.Row row = result.next(); if (result.hasNext()) { throw new AssertionError(); } final int correlationArray = row.get(0).toInt(); final DbInsertQuery insertQuery = new DbInsertQuery.Builder(table) .put(table.getConceptColumnIndex(), _concept) .put(table.getCorrelationArrayColumnIndex(), correlationArray) .build(); final int newAccId = db.insert(insertQuery); final StringQueriesTable strings = Tables.stringQueries; final DbQuery stringsQuery = new DbQuery.Builder(strings) .where(strings.getDynamicAcceptationColumnIndex(), linkedAcceptation) .where(strings.getMainAcceptationColumnIndex(), linkedAcceptation) .select(strings.getStringAlphabetColumnIndex(), strings.getStringColumnIndex(), strings.getMainStringColumnIndex()); final ImmutableIntList.Builder alphabetsBuilder = new ImmutableIntList.Builder(); final ImmutableList.Builder<String> stringsBuilder = new ImmutableList.Builder<>(); final ImmutableList.Builder<String> mainStringsBuilder = new ImmutableList.Builder<>(); for (DbResult.Row r : DbManager.getInstance().attach(stringsQuery)) { alphabetsBuilder.add(r.get(0).toInt()); stringsBuilder.add(r.get(1).toText()); mainStringsBuilder.add(r.get(2).toText()); } final ImmutableIntList alphabets = alphabetsBuilder.build(); final ImmutableList<String> strs = stringsBuilder.build(); final ImmutableList<String> mainStrs = mainStringsBuilder.build(); final int length = alphabets.size(); for (int i = 0; i < length; i++) { final DbInsertQuery iQuery = new DbInsertQuery.Builder(strings) .put(strings.getDynamicAcceptationColumnIndex(), newAccId) .put(strings.getMainAcceptationColumnIndex(), newAccId) .put(strings.getStringAlphabetColumnIndex(), alphabets.valueAt(i)) .put(strings.getStringColumnIndex(), strs.valueAt(i)) .put(strings.getMainStringColumnIndex(), mainStrs.valueAt(i)) .build(); if (db.insert(iQuery) == null) { throw new AssertionError(); } } } private void showFeedback(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } }
Refresh AcceptationDetailsActivity after executing action
app/src/main/java/sword/langbook3/android/AcceptationDetailsActivity.java
Refresh AcceptationDetailsActivity after executing action
<ide><path>pp/src/main/java/sword/langbook3/android/AcceptationDetailsActivity.java <ide> private AcceptationDetailsActivityState _state; <ide> <ide> private boolean _shouldShowBunchChildrenQuizMenuOption; <add> private ListView _listView; <ide> private AcceptationDetailsAdapter _listAdapter; <ide> <ide> public static void open(Context context, int staticAcceptation, int dynamicAcceptation) { <ide> return result.toArray(new AcceptationDetailsAdapter.Item[result.size()]); <ide> } <ide> <add> private void updateAdapter() { <add> _listAdapter = new AcceptationDetailsAdapter(getAdapterItems(_staticAcceptation)); <add> _listView.setAdapter(_listAdapter); <add> } <add> <ide> @Override <ide> public void onCreate(Bundle savedInstanceState) { <ide> super.onCreate(savedInstanceState); <ide> <ide> _staticAcceptation = getIntent().getIntExtra(ArgKeys.STATIC_ACCEPTATION, 0); <ide> _concept = conceptFromAcceptation(DbManager.getInstance().getDatabase(), _staticAcceptation); <add> _listView = findViewById(R.id.listView); <add> <ide> if (_concept != 0) { <del> _listAdapter = new AcceptationDetailsAdapter(getAdapterItems(_staticAcceptation)); <del> <del> ListView listView = findViewById(R.id.listView); <del> listView.setAdapter(_listAdapter); <del> listView.setOnItemClickListener(this); <del> listView.setOnItemLongClickListener(this); <add> updateAdapter(); <add> _listView.setOnItemClickListener(this); <add> _listView.setOnItemLongClickListener(this); <ide> <ide> switch (_state.getIntrinsicState()) { <ide> case IntrinsicStates.DELETE_ACCEPTATION: <ide> if (!deleteBunchConceptForConcept(DbManager.getInstance().getDatabase(), _concept)) { <ide> throw new AssertionError(); <ide> } <add> updateAdapter(); <ide> showFeedback(getString(R.string.deleteSupertypeFeedback)); <add> invalidateOptionsMenu(); <ide> break; <ide> <ide> case IntrinsicStates.LINKING_CONCEPT: <ide> showFeedback("Acceptation linked"); <ide> } <ide> _state.clearLinkedAcceptation(); <add> updateAdapter(); <ide> break; <ide> <ide> case IntrinsicStates.DELETING_FROM_BUNCH: <ide> throw new AssertionError(); <ide> } <ide> <add> updateAdapter(); <ide> showFeedback(getString(R.string.deleteFromBunchFeedback, bunchText)); <ide> break; <ide> <ide> throw new AssertionError(); <ide> } <ide> <add> updateAdapter(); <ide> showFeedback(getString(R.string.deleteAcceptationFromBunchFeedback, accToDeleteText)); <ide> break; <ide> <ide> _state.setLinkedAcceptation(data.getIntExtra(AcceptationPickerActivity.ResultKeys.ACCEPTATION, 0)); <ide> showLinkModeSelectorDialog(); <ide> } <add> else { <add> updateAdapter(); <add> } <ide> } <ide> else if (requestCode == REQUEST_CODE_PICK_ACCEPTATION) { <ide> final int pickedAcceptation = data.getIntExtra(AcceptationPickerActivity.ResultKeys.ACCEPTATION, 0); <ide> final Database db = DbManager.getInstance().getDatabase(); <ide> final int message = addAcceptationInBunch(db, _concept, pickedAcceptation)? R.string.includeInBunchOk : R.string.includeInBunchKo; <add> updateAdapter(); <ide> showFeedback(getString(message)); <ide> } <ide> else if (requestCode == REQUEST_CODE_PICK_BUNCH) { <ide> final Database db = DbManager.getInstance().getDatabase(); <ide> final int pickedBunch = (pickedAcceptation != 0)? conceptFromAcceptation(db, pickedAcceptation) : 0; <ide> final int message = addAcceptationInBunch(db, pickedBunch, _staticAcceptation)? R.string.includeInBunchOk : R.string.includeInBunchKo; <add> updateAdapter(); <ide> showFeedback(getString(message)); <ide> } <ide> else if (requestCode == REQUEST_CODE_PICK_SUPERTYPE) { <ide> final int pickedConcept = (pickedAcceptation != 0)? conceptFromAcceptation(db, pickedAcceptation) : 0; <ide> insertBunchConcept(db, pickedConcept, _concept); <ide> showFeedback(getString(R.string.includeSupertypeOk)); <add> updateAdapter(); <add> invalidateOptionsMenu(); <ide> } <ide> } <ide> }
Java
apache-2.0
ca61f9be357dc2091c871a0a76724d417e082045
0
cuba-platform/cuba,dimone-kun/cuba,dimone-kun/cuba,cuba-platform/cuba,dimone-kun/cuba,cuba-platform/cuba
/* * Copyright (c) 2008-2016 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.haulmont.cuba.core; import com.haulmont.bali.util.Preconditions; import com.haulmont.chile.core.model.MetaClass; import com.haulmont.chile.core.model.MetaProperty; import com.haulmont.cuba.core.entity.BaseEntityInternalAccess; import com.haulmont.cuba.core.entity.BaseGenericIdEntity; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.global.Metadata; import com.haulmont.cuba.core.global.PersistenceHelper; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.descriptors.changetracking.ChangeTracker; import org.eclipse.persistence.indirection.ValueHolderInterface; import org.eclipse.persistence.internal.descriptors.changetracking.AttributeChangeListener; import org.eclipse.persistence.internal.helper.DatabaseField; import org.eclipse.persistence.internal.indirection.DatabaseValueHolder; import org.eclipse.persistence.internal.sessions.AbstractRecord; import org.eclipse.persistence.internal.sessions.ObjectChangeSet; import org.eclipse.persistence.mappings.DatabaseMapping; import org.eclipse.persistence.mappings.converters.Converter; import org.eclipse.persistence.mappings.foundation.AbstractColumnMapping; import org.eclipse.persistence.queries.FetchGroup; import org.eclipse.persistence.queries.FetchGroupTracker; import org.eclipse.persistence.sessions.Session; import org.eclipse.persistence.sessions.changesets.ChangeRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.Nullable; import javax.inject.Inject; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.Vector; /** * Utility class to provide common functionality related to persistence. * <p/> Implemented as Spring bean to allow extension in application projects. * <p/> A reference to this class can be obtained either via DI or by * {@link com.haulmont.cuba.core.Persistence#getTools()} method. */ @Component(PersistenceTools.NAME) public class PersistenceTools { public static final String NAME = "cuba_PersistenceTools"; protected final Logger log = LoggerFactory.getLogger(getClass()); @Inject protected Persistence persistence; @Inject protected Metadata metadata; /** * Returns the set of dirty attributes (changed since the last load from the database). * <p> If the entity is new, returns all its attributes. * <p> If the entity is not persistent or not in the Managed state, returns empty set. * * @param entity entity instance * @return dirty attribute names * @see #isDirty(Entity, String...) */ public Set<String> getDirtyFields(Entity entity) { Preconditions.checkNotNullArgument(entity, "entity is null"); if (!(entity instanceof ChangeTracker) || !PersistenceHelper.isManaged(entity)) return Collections.emptySet(); HashSet<String> result = new HashSet<>(); if (PersistenceHelper.isNew(entity)) { for (MetaProperty property : metadata.getClassNN(entity.getClass()).getProperties()) { if (metadata.getTools().isPersistent(property)) result.add(property.getName()); } } else { ObjectChangeSet objectChanges = ((AttributeChangeListener)((ChangeTracker) entity)._persistence_getPropertyChangeListener()).getObjectChangeSet(); if (objectChanges != null) // can be null for example in AFTER_DELETE entity listener result.addAll(objectChanges.getChangedAttributeNames()); } return result; } /** * Returns true if at least one of the given attributes is dirty (i.e. changed since the last load from the database). * <p> If the entity is new, always returns true. * <p> If the entity is not persistent or not in the Managed state, always returns false. * @param entity entity instance * @param attributes attributes to check * @see #getDirtyFields(Entity) */ public boolean isDirty(Entity entity, String... attributes) { Set<String> dirtyFields = getDirtyFields(entity); for (String attribute : attributes) { if (dirtyFields.contains(attribute)) return true; } return false; } /** * Returns an old value of an attribute changed in the current transaction. The entity must be in the Managed state. * @param entity entity instance * @param attribute attribute name * @return an old value stored in the database. For a new entity returns null. * @throws IllegalArgumentException if the entity is not persistent or not in the Managed state */ @Nullable public Object getOldValue(Entity entity, String attribute) { Preconditions.checkNotNullArgument(entity, "entity is null"); if (!(entity instanceof ChangeTracker) || !PersistenceHelper.isManaged(entity)) throw new IllegalArgumentException("The entity " + entity + " is not a ChangeTracker"); if (!PersistenceHelper.isManaged(entity)) throw new IllegalArgumentException("The entity " + entity + " is not in the Managed state"); if (PersistenceHelper.isNew(entity)) { return null; } else { ObjectChangeSet objectChanges = ((AttributeChangeListener)((ChangeTracker) entity)._persistence_getPropertyChangeListener()).getObjectChangeSet(); if (objectChanges != null) { // can be null for example in AFTER_DELETE entity listener ChangeRecord changeRecord = objectChanges.getChangesForAttributeNamed(attribute); if (changeRecord != null) return changeRecord.getOldValue(); } } return null; } /** * Checks if the property is loaded from DB. * * @param entity entity * @param property name of the property * @return true if loaded */ public boolean isLoaded(Object entity, String property) { return PersistenceHelper.isLoaded(entity, property); } /** * Returns an ID of directly referenced entity without loading it from DB. * * <p>Use this method only when the given entity has been loaded <b>without a view</b>. If the entity is loaded with a view * and the view contains the reference attribute, you can get the reference value from the corresponding getter. * If the view does not contain the reference, the returned {@link RefId} will have {@link RefId#isLoaded()} = false. * * <p>Usage example: * <pre> * PersistenceTools.RefId refId = persistenceTools.getReferenceId(doc, "currency"); * if (refId.isLoaded()) { * String currencyCode = (String) refId.getValue(); * } * </pre> * * @param entity entity instance in managed state * @param property name of reference property * @return {@link RefId} instance which contains the referenced entity ID * @throws IllegalArgumentException if the specified property is not a reference * @throws IllegalStateException if the entity is not in Managed state * @throws RuntimeException if anything goes wrong when retrieving the ID */ public RefId getReferenceId(BaseGenericIdEntity entity, String property) { MetaClass metaClass = metadata.getClassNN(entity.getClass()); MetaProperty metaProperty = metaClass.getPropertyNN(property); if (!metaProperty.getRange().isClass() || metaProperty.getRange().getCardinality().isMany()) throw new IllegalArgumentException("Property is not a reference"); if (!PersistenceHelper.isManaged(entity)) throw new IllegalStateException("Entity must be in managed state"); String[] inaccessibleAttributes = BaseEntityInternalAccess.getInaccessibleAttributes(entity); if (inaccessibleAttributes != null) { for (String inaccessibleAttr : inaccessibleAttributes) { if (inaccessibleAttr.equals(property)) return RefId.createNotLoaded(property); } } if (entity instanceof FetchGroupTracker) { FetchGroup fetchGroup = ((FetchGroupTracker) entity)._persistence_getFetchGroup(); if (fetchGroup != null) { if (!fetchGroup.getAttributeNames().contains(property)) return RefId.createNotLoaded(property); else { Entity refEntity = (Entity) entity.getValue(property); return RefId.create(property, refEntity == null ? null : refEntity.getId()); } } } try { Class<?> declaringClass = metaProperty.getDeclaringClass(); if (declaringClass == null) { throw new RuntimeException("Property does not belong to persistent class"); } Method vhMethod = declaringClass.getDeclaredMethod(String.format("_persistence_get_%s_vh", property)); vhMethod.setAccessible(true); ValueHolderInterface vh = (ValueHolderInterface) vhMethod.invoke(entity); if (vh instanceof DatabaseValueHolder) { AbstractRecord row = ((DatabaseValueHolder) vh).getRow(); if (row != null) { Session session = persistence.getEntityManager().getDelegate().unwrap(Session.class); ClassDescriptor descriptor = session.getDescriptor(entity); DatabaseMapping mapping = descriptor.getMappingForAttributeName(property); Vector<DatabaseField> fields = mapping.getFields(); if (fields.size() != 1) { throw new IllegalStateException("Invalid number of columns in mapping: " + fields); } Object value = row.get(fields.get(0)); if (value != null) { ClassDescriptor refDescriptor = mapping.getReferenceDescriptor(); DatabaseMapping refMapping = refDescriptor.getMappingForAttributeName(metadata.getTools().getPrimaryKeyName(metaClass)); if (refMapping instanceof AbstractColumnMapping) { Converter converter = ((AbstractColumnMapping) refMapping).getConverter(); if (converter != null) { return RefId.create(property, converter.convertDataValueToObjectValue(value, session)); } } } return RefId.create(property, value); } } return RefId.createNotLoaded(property); } catch (Exception e) { throw new RuntimeException( String.format("Error retrieving reference ID from %s.%s", entity.getClass().getSimpleName(), property), e); } } /** * A wrapper for the reference ID value returned by {@link #getReferenceId(BaseGenericIdEntity, String)} method. * @see #isLoaded() * @see #getValue() */ public static class RefId { private String name; private final boolean loaded; private final Object value; private RefId(String name, boolean loaded, Object value) { this.name = name; this.loaded = loaded; this.value = value; } public static RefId create(String name, Object value) { return new RefId(name, true, value); } public static RefId createNotLoaded(String name) { return new RefId(name, false, true); } /** * Returns true if the reference ID has been loaded and can be retrieved by calling {@link #getValue()} */ public boolean isLoaded() { return loaded; } /** * Returns the reference ID value (can be null) if {@link #isLoaded()} is true * @throws IllegalStateException if {@link #isLoaded()} is false */ @Nullable public Object getValue() { if (!loaded) throw new IllegalStateException("Property '" + name + "' has not been loaded"); return value; } } }
modules/core/src/com/haulmont/cuba/core/PersistenceTools.java
/* * Copyright (c) 2008-2016 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.haulmont.cuba.core; import com.haulmont.bali.util.Preconditions; import com.haulmont.chile.core.model.MetaClass; import com.haulmont.chile.core.model.MetaProperty; import com.haulmont.cuba.core.entity.BaseEntityInternalAccess; import com.haulmont.cuba.core.entity.BaseGenericIdEntity; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.global.Metadata; import com.haulmont.cuba.core.global.PersistenceHelper; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.descriptors.changetracking.ChangeTracker; import org.eclipse.persistence.indirection.ValueHolderInterface; import org.eclipse.persistence.internal.descriptors.changetracking.AttributeChangeListener; import org.eclipse.persistence.internal.helper.DatabaseField; import org.eclipse.persistence.internal.indirection.DatabaseValueHolder; import org.eclipse.persistence.internal.sessions.AbstractRecord; import org.eclipse.persistence.internal.sessions.ObjectChangeSet; import org.eclipse.persistence.mappings.DatabaseMapping; import org.eclipse.persistence.mappings.converters.Converter; import org.eclipse.persistence.mappings.foundation.AbstractColumnMapping; import org.eclipse.persistence.queries.FetchGroup; import org.eclipse.persistence.queries.FetchGroupTracker; import org.eclipse.persistence.sessions.Session; import org.eclipse.persistence.sessions.changesets.ChangeRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.Nullable; import javax.inject.Inject; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.Vector; /** * Utility class to provide common functionality related to persistence. * <p/> Implemented as Spring bean to allow extension in application projects. * <p/> A reference to this class can be obtained either via DI or by * {@link com.haulmont.cuba.core.Persistence#getTools()} method. */ @Component(PersistenceTools.NAME) public class PersistenceTools { public static final String NAME = "cuba_PersistenceTools"; protected final Logger log = LoggerFactory.getLogger(getClass()); @Inject protected Persistence persistence; @Inject protected Metadata metadata; /** * Returns the set of dirty attributes (changed since the last load from the database). * <p> If the entity is new, returns all its attributes. * <p> If the entity is not persistent or not in the Managed state, returns empty set. * * @param entity entity instance * @return dirty attribute names * @see #isDirty(Entity, String...) */ public Set<String> getDirtyFields(Entity entity) { Preconditions.checkNotNullArgument(entity, "entity is null"); if (!(entity instanceof ChangeTracker) || !PersistenceHelper.isManaged(entity)) return Collections.emptySet(); HashSet<String> result = new HashSet<>(); if (PersistenceHelper.isNew(entity)) { for (MetaProperty property : metadata.getClassNN(entity.getClass()).getProperties()) { if (metadata.getTools().isPersistent(property)) result.add(property.getName()); } } else { ObjectChangeSet objectChanges = ((AttributeChangeListener)((ChangeTracker) entity)._persistence_getPropertyChangeListener()).getObjectChangeSet(); if (objectChanges != null) // can be null for example in AFTER_DELETE entity listener result.addAll(objectChanges.getChangedAttributeNames()); } return result; } /** * Returns true if at least one of the given attributes is dirty (i.e. changed since the last load from the database). * <p> If the entity is new, always returns true. * <p> If the entity is not persistent or not in the Managed state, always returns false. * @param entity entity instance * @param attributes attributes to check * @see #getDirtyFields(Entity) */ public boolean isDirty(Entity entity, String... attributes) { Set<String> dirtyFields = getDirtyFields(entity); for (String attribute : attributes) { if (dirtyFields.contains(attribute)) return true; } return false; } /** * Returns an old value of an attribute changed in the current transaction. The entity must be in the Managed state. * @param entity entity instance * @param attribute attribute name * @return an old value stored in the database. For a new entity returns null. * @throws IllegalArgumentException if the entity is not persistent or not in the Managed state */ @Nullable public Object getOldValue(Entity entity, String attribute) { Preconditions.checkNotNullArgument(entity, "entity is null"); if (!(entity instanceof ChangeTracker) || !PersistenceHelper.isManaged(entity)) throw new IllegalArgumentException("The entity " + entity + " is not a ChangeTracker"); if (!PersistenceHelper.isManaged(entity)) throw new IllegalArgumentException("The entity " + entity + " is not in the Managed state"); if (PersistenceHelper.isNew(entity)) { return null; } else { ObjectChangeSet objectChanges = ((AttributeChangeListener)((ChangeTracker) entity)._persistence_getPropertyChangeListener()).getObjectChangeSet(); if (objectChanges != null) { // can be null for example in AFTER_DELETE entity listener ChangeRecord changeRecord = objectChanges.getChangesForAttributeNamed(attribute); if (changeRecord != null) return changeRecord.getOldValue(); } } return null; } /** * Checks if the property is loaded from DB. * * @param entity entity * @param property name of the property * @return true if loaded */ public boolean isLoaded(Object entity, String property) { return PersistenceHelper.isLoaded(entity, property); } /** * Returns an ID of directly referenced entity without loading it from DB. * * <p>Use this method only when the given entity has been loaded <b>without a view</b>. If the entity is loaded with a view * and the view contains the reference attribute, you can get the reference value from the corresponding getter. * If the view does not contain the reference, the returned {@link RefId} will have {@link RefId#isLoaded()} = false. * * <p>Usage example: * <pre> * PersistenceTools.RefId refId = persistenceTools.getReferenceId(doc, "currency"); * if (refId.isLoaded()) { * String currencyCode = (String) refId.getValue(); * } * </pre> * * @param entity entity instance in managed state * @param property name of reference property * @return {@link RefId} instance which contains the referenced entity ID * @throws IllegalArgumentException if the specified property is not a reference * @throws IllegalStateException if the entity is not in Managed state * @throws RuntimeException if anything goes wrong when retrieving the ID */ public RefId getReferenceId(BaseGenericIdEntity entity, String property) { MetaClass metaClass = metadata.getClassNN(entity.getClass()); MetaProperty metaProperty = metaClass.getPropertyNN(property); if (!metaProperty.getRange().isClass() || metaProperty.getRange().getCardinality().isMany()) throw new IllegalArgumentException("Property is not a reference"); if (!PersistenceHelper.isManaged(entity)) throw new IllegalStateException("Entity must be in managed state"); String[] inaccessibleAttributes = BaseEntityInternalAccess.getInaccessibleAttributes(entity); if (inaccessibleAttributes != null) { for (String inaccessibleAttr : inaccessibleAttributes) { if (inaccessibleAttr.equals(property)) return RefId.createNotLoaded(property); } } if (entity instanceof FetchGroupTracker) { FetchGroup fetchGroup = ((FetchGroupTracker) entity)._persistence_getFetchGroup(); if (fetchGroup != null) { if (!fetchGroup.getAttributeNames().contains(property)) return RefId.createNotLoaded(property); else { Entity refEntity = (Entity) entity.getValue(property); return RefId.create(property, refEntity == null ? null : refEntity.getId()); } } } try { Method vhMethod = entity.getClass().getMethod("_persistence_get_" + property + "_vh"); vhMethod.setAccessible(true); ValueHolderInterface vh = (ValueHolderInterface) vhMethod.invoke(entity); if (vh instanceof DatabaseValueHolder) { AbstractRecord row = ((DatabaseValueHolder) vh).getRow(); if (row != null) { Session session = persistence.getEntityManager().getDelegate().unwrap(Session.class); ClassDescriptor descriptor = session.getDescriptor(entity); DatabaseMapping mapping = descriptor.getMappingForAttributeName(property); Vector<DatabaseField> fields = mapping.getFields(); if (fields.size() != 1) { throw new IllegalStateException("Invalid number of columns in mapping: " + fields); } Object value = row.get(fields.get(0)); if (value != null) { ClassDescriptor refDescriptor = mapping.getReferenceDescriptor(); DatabaseMapping refMapping = refDescriptor.getMappingForAttributeName(metadata.getTools().getPrimaryKeyName(metaClass)); if (refMapping instanceof AbstractColumnMapping) { Converter converter = ((AbstractColumnMapping) refMapping).getConverter(); if (converter != null) { return RefId.create(property, converter.convertDataValueToObjectValue(value, session)); } } } return RefId.create(property, value); } } return RefId.createNotLoaded(property); } catch (Exception e) { throw new RuntimeException("Error retrieving reference ID from " + entity.getClass().getSimpleName() + "." + property, e); } } /** * A wrapper for the reference ID value returned by {@link #getReferenceId(BaseGenericIdEntity, String)} method. * @see #isLoaded() * @see #getValue() */ public static class RefId { private String name; private final boolean loaded; private final Object value; private RefId(String name, boolean loaded, Object value) { this.name = name; this.loaded = loaded; this.value = value; } public static RefId create(String name, Object value) { return new RefId(name, true, value); } public static RefId createNotLoaded(String name) { return new RefId(name, false, true); } /** * Returns true if the reference ID has been loaded and can be retrieved by calling {@link #getValue()} */ public boolean isLoaded() { return loaded; } /** * Returns the reference ID value (can be null) if {@link #isLoaded()} is true * @throws IllegalStateException if {@link #isLoaded()} is false */ @Nullable public Object getValue() { if (!loaded) throw new IllegalStateException("Property '" + name + "' has not been loaded"); return value; } } }
PL-6482 Noisy autocomplete with compiled enity classes
modules/core/src/com/haulmont/cuba/core/PersistenceTools.java
PL-6482 Noisy autocomplete with compiled enity classes
<ide><path>odules/core/src/com/haulmont/cuba/core/PersistenceTools.java <ide> } <ide> <ide> try { <del> Method vhMethod = entity.getClass().getMethod("_persistence_get_" + property + "_vh"); <add> Class<?> declaringClass = metaProperty.getDeclaringClass(); <add> if (declaringClass == null) { <add> throw new RuntimeException("Property does not belong to persistent class"); <add> } <add> <add> Method vhMethod = declaringClass.getDeclaredMethod(String.format("_persistence_get_%s_vh", property)); <ide> vhMethod.setAccessible(true); <add> <ide> ValueHolderInterface vh = (ValueHolderInterface) vhMethod.invoke(entity); <ide> if (vh instanceof DatabaseValueHolder) { <ide> AbstractRecord row = ((DatabaseValueHolder) vh).getRow(); <ide> } <ide> return RefId.createNotLoaded(property); <ide> } catch (Exception e) { <del> throw new RuntimeException("Error retrieving reference ID from " <del> + entity.getClass().getSimpleName() + "." + property, e); <add> throw new RuntimeException( <add> String.format("Error retrieving reference ID from %s.%s", entity.getClass().getSimpleName(), property), <add> e); <ide> } <ide> } <ide>
Java
apache-2.0
76c1b24fb4540ed0661596bd3a7ca9bb47d00d78
0
williamchand/linebotsdk
package com.example.bot.spring; import java.io.IOException; import java.io.OutputStream; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.function.Consumer; import java.net.URISyntaxException; import java.net.URI; import java.sql.*; import javax.sql.DataSource;; import java.util.Timer; import java.util.TimerTask; import java.lang.Override; import com.heroku.sdk.jdbc.DatabaseUrl; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.google.common.io.ByteStreams; import com.linecorp.bot.client.LineMessagingClient; import com.linecorp.bot.client.MessageContentResponse; import com.linecorp.bot.model.ReplyMessage; import com.linecorp.bot.model.Multicast; import com.linecorp.bot.model.PushMessage; import com.linecorp.bot.model.action.MessageAction; import com.linecorp.bot.model.action.PostbackAction; import com.linecorp.bot.model.action.URIAction; import com.linecorp.bot.model.event.BeaconEvent; import com.linecorp.bot.model.event.Event; import com.linecorp.bot.model.event.FollowEvent; import com.linecorp.bot.model.event.JoinEvent; import com.linecorp.bot.model.event.MessageEvent; import com.linecorp.bot.model.event.PostbackEvent; import com.linecorp.bot.model.event.UnfollowEvent; import com.linecorp.bot.model.event.message.AudioMessageContent; import com.linecorp.bot.model.event.message.ImageMessageContent; import com.linecorp.bot.model.event.message.LocationMessageContent; import com.linecorp.bot.model.event.message.StickerMessageContent; import com.linecorp.bot.model.event.message.TextMessageContent; import com.linecorp.bot.model.event.message.VideoMessageContent; import com.linecorp.bot.model.event.source.GroupSource; import com.linecorp.bot.model.event.source.RoomSource; import com.linecorp.bot.model.event.source.Source; import com.linecorp.bot.model.message.AudioMessage; import com.linecorp.bot.model.message.ImageMessage; import com.linecorp.bot.model.message.ImagemapMessage; import com.linecorp.bot.model.message.LocationMessage; import com.linecorp.bot.model.message.Message; import com.linecorp.bot.model.message.StickerMessage; import com.linecorp.bot.model.message.TemplateMessage; import com.linecorp.bot.model.message.TextMessage; import com.linecorp.bot.model.message.VideoMessage; import com.linecorp.bot.model.message.imagemap.ImagemapArea; import com.linecorp.bot.model.message.imagemap.ImagemapBaseSize; import com.linecorp.bot.model.message.imagemap.MessageImagemapAction; import com.linecorp.bot.model.message.imagemap.URIImagemapAction; import com.linecorp.bot.model.message.template.ButtonsTemplate; import com.linecorp.bot.model.message.template.CarouselColumn; import com.linecorp.bot.model.message.template.CarouselTemplate; import com.linecorp.bot.model.message.template.ConfirmTemplate; import com.linecorp.bot.model.profile.UserProfileResponse; import com.linecorp.bot.model.response.BotApiResponse; import com.linecorp.bot.spring.boot.annotation.EventMapping; import com.linecorp.bot.spring.boot.annotation.LineMessageHandler; import lombok.NonNull; import lombok.Value; import lombok.extern.slf4j.Slf4j; @Slf4j @LineMessageHandler @RestController public class KitchenSinkController { @Autowired private LineMessagingClient lineMessagingClient; private String TokenCallback1; @EventMapping public void handleTextMessageEvent(MessageEvent<TextMessageContent> event) throws Exception { TextMessageContent message = event.getMessage(); handleTextContent(event.getReplyToken(), event, message); } @EventMapping public void handleStickerMessageEvent(MessageEvent<StickerMessageContent> event) { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleLocationMessageEvent(MessageEvent<LocationMessageContent> event) { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleImageMessageEvent(MessageEvent<ImageMessageContent> event) throws IOException { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleAudioMessageEvent(MessageEvent<AudioMessageContent> event) throws IOException { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleVideoMessageEvent(MessageEvent<VideoMessageContent> event) throws IOException { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleUnfollowEvent(UnfollowEvent event) { log.info("unfollowed this bot: {}", event); } @EventMapping public void handleFollowEvent(FollowEvent event) { String replyToken = event.getReplyToken(); this.replyText(replyToken, "bot telah di ikuti info lebih lanjut /help"); } @EventMapping public void handleJoinEvent(JoinEvent event) { String replyToken = event.getReplyToken(); this.replyText(replyToken, "Bot telah bergabung ke grup info lebih lanjut /help" ); } @EventMapping public void handlePostbackEvent(PostbackEvent event) { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleBeaconEvent(BeaconEvent event) { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleOtherEvent(Event event) { log.info("Received message(Ignored): {}", event); } private void reply(@NonNull String replyToken, @NonNull Message message) { reply(replyToken, Collections.singletonList(message)); } private void reply(@NonNull String replyToken, @NonNull List<Message> messages) { try { BotApiResponse apiResponse = lineMessagingClient .replyMessage(new ReplyMessage(replyToken, messages)) .get(); log.info("Sent messages: {}", apiResponse); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } private void replyText(@NonNull String replyToken, @NonNull String message) { if (replyToken.isEmpty()) { throw new IllegalArgumentException("replyToken must not be empty"); } if (message.length() > 1000) { message = message.substring(0, 1000 - 2); } this.reply(replyToken, new TextMessage(message)); } private void push(@NonNull String To, @NonNull Message message) { push(To, Collections.singletonList(message)); } private void push(@NonNull String To, @NonNull List<Message> messages) { try { BotApiResponse apiResponse = lineMessagingClient .pushMessage(new PushMessage(To, messages)) .get(); log.info("Sent messages: {}", apiResponse); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } private void pushText(@NonNull String To, @NonNull String message) { if (To.isEmpty()) { throw new IllegalArgumentException("replyToken must not be empty"); } if (message.length() > 1000) { message = message.substring(0, 1000 - 2); } this.push(To, new TextMessage(message)); } private Timer startTimer() { Timer timer =new Timer(); return timer; } private String DB1(Connection connection){ String Messages=""; try{ Statement stmt = connection.createStatement(); stmt.executeUpdate("DROP TABLE IF EXISTS ticks"); stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now() + INTERVAL '7 HOUR')"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); while (rs.next()) { Messages = "Waktu Indonesia Barat: " + rs.getTimestamp("tick"); } }catch(SQLException e){ Messages = e.getMessage(); } return Messages; } private void handleTextContent(String replyToken, Event event, TextMessageContent content) throws Exception { Timer t0; String text = content.getText(); Connection connection = getConnection(); log.info("Got text message from {}: {}", replyToken, text); if (text.indexOf("/create")>=0){ String userId = event.getSource().getUserId(); if (userId != null) { lineMessagingClient .getProfile(userId) .whenComplete((profile, throwable) -> { if (throwable != null) { this.replyText(replyToken, throwable.getMessage()); return; } this.reply( replyToken, Arrays.asList(new TextMessage( "Id: " + userId), new TextMessage( "Display name: " + profile.getDisplayName()), new TextMessage( "Status message: " + profile.getStatusMessage())) ); }); } else { this.replyText(replyToken, "Tolong izinkan Bot mengakses akun"); } }else if (text.indexOf("/join")>=0){ String imageUrl = createUri("/static/buttons/1040.jpg"); ButtonsTemplate buttonsTemplate = new ButtonsTemplate( imageUrl, "My button sample", "Hello, my button", Arrays.asList( new URIAction("Go to line.me", "https://line.me"), new PostbackAction("Say hello1", DB1(connection)), new PostbackAction("hello2", "hello", "hello"), new MessageAction("Say message", "Rice") )); TemplateMessage templateMessage = new TemplateMessage("Button alt text", buttonsTemplate); this.reply(replyToken, templateMessage); }else if (text.indexOf("/start")>=0){ String imageUrl = createUri("/static/buttons/1040.jpg"); ButtonsTemplate buttonsTemplate = new ButtonsTemplate( imageUrl, "My button sample", "Hello, my button", Arrays.asList( new URIAction("Go to line.me", "https://line.me"), new PostbackAction("Say hello1", "hello"), new PostbackAction("hello2", "hello", "hello"), new MessageAction("Say message", "Rice") )); TemplateMessage templateMessage = new TemplateMessage("Button alt text", buttonsTemplate); this.reply(replyToken, templateMessage); }else if(text.indexOf("/time")>=0){ try{ Statement stmt = connection.createStatement(); stmt.executeUpdate("DROP TABLE IF EXISTS ticks"); stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now() + INTERVAL '7 HOUR')"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); while (rs.next()) { this.replyText(replyToken,"Waktu Indonesia Barat: " + rs.getTimestamp("tick")); } }catch(SQLException e){ this.replyText(replyToken,e.getMessage()); } }else if(text.indexOf("/delay")>=0){ Source source = event.getSource(); String id=""; this.TokenCallback1 = replyToken; if (source instanceof GroupSource) { id = ((GroupSource) source).getGroupId(); } if (id ==""){ id = event.getSource().getUserId(); } t0 = startTimer(); t0.schedule( new TimerTask() { @Override public void run() { try{ Connection connection = KitchenSinkController.getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("DROP TABLE IF EXISTS ticks"); stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now() + INTERVAL '7 HOUR')"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); while (rs.next()) { KitchenSinkController.this.replyText(KitchenSinkController.this.TokenCallback1,"Read from DB: " + rs.getTimestamp("tick")); } }catch(SQLException e){ KitchenSinkController.this.replyText(KitchenSinkController.this.TokenCallback1,e.getMessage()); }catch(URISyntaxException err){ KitchenSinkController.this.replyText(KitchenSinkController.this.TokenCallback1,err.getMessage()); } t0.cancel(); } }, 5000, 100); // Every second }else if (text.indexOf("/help")>=0){ this.replyText(replyToken, "feature /help : bantuan\n"+"/imagemap:gambar yang dapat diklik\n"+"/buttons:tombol\n"+ "/question:pertanyaan\n"+"/carousel:carousel\n"+"/leave:keluar dari grup\n"+"/profile:user ID\n"); }else if (text.indexOf("/leave")>=0){ Source source = event.getSource(); if (source instanceof GroupSource) { this.replyText(replyToken, "Bot meninggalkan grup"); lineMessagingClient.leaveGroup(((GroupSource) source).getGroupId()).get(); } else if (source instanceof RoomSource) { this.replyText(replyToken, "Bot meninggalkan ruangan"); lineMessagingClient.leaveRoom(((RoomSource) source).getRoomId()).get(); } else { this.replyText(replyToken, "ini room 1:1 tidak bisa menggunakan perintah /leave"); } }else{ log.info("Ignore message {}: {}", replyToken, text); } } private static Connection getConnection() throws URISyntaxException, SQLException { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath(); return DriverManager.getConnection(dbUrl, username, password); } private static String createUri(String path) { return ServletUriComponentsBuilder.fromCurrentContextPath() .path(path).build() .toUriString(); } private void system(String... args) { ProcessBuilder processBuilder = new ProcessBuilder(args); try { Process start = processBuilder.start(); int i = start.waitFor(); log.info("result: {} => {}", Arrays.toString(args), i); } catch (IOException e) { throw new UncheckedIOException(e); } catch (InterruptedException e) { log.info("Interrupted", e); Thread.currentThread().interrupt(); } } private static DownloadedContent saveContent(String ext, MessageContentResponse responseBody) { log.info("Got content-type: {}", responseBody); DownloadedContent tempFile = createTempFile(ext); try (OutputStream outputStream = Files.newOutputStream(tempFile.path)) { ByteStreams.copy(responseBody.getStream(), outputStream); log.info("Saved {}: {}", ext, tempFile); return tempFile; } catch (IOException e) { throw new UncheckedIOException(e); } } private static DownloadedContent createTempFile(String ext) { String fileName = LocalDateTime.now().toString() + '-' + UUID.randomUUID().toString() + '.' + ext; Path tempFile = KitchenSinkApplication.downloadedContentDir.resolve(fileName); tempFile.toFile().deleteOnExit(); return new DownloadedContent( tempFile, createUri("/downloaded/" + tempFile.getFileName())); } @Value public static class DownloadedContent { Path path; String uri; } @RequestMapping("/greeting") public Greeting greeting(@RequestParam(value="UserId", defaultValue="") String User,@RequestParam(value="message", defaultValue="") String message) { this.pushText(User, message); return new Greeting(User,message); } }
sample-spring-boot-kitchensink/src/main/java/com/example/bot/spring/KitchenSinkController.java
package com.example.bot.spring; import java.io.IOException; import java.io.OutputStream; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.function.Consumer; import java.net.URISyntaxException; import java.net.URI; import java.sql.*; import javax.sql.DataSource;; import java.util.Timer; import java.util.TimerTask; import java.lang.Override; import com.heroku.sdk.jdbc.DatabaseUrl; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.google.common.io.ByteStreams; import com.linecorp.bot.client.LineMessagingClient; import com.linecorp.bot.client.MessageContentResponse; import com.linecorp.bot.model.ReplyMessage; import com.linecorp.bot.model.Multicast; import com.linecorp.bot.model.PushMessage; import com.linecorp.bot.model.action.MessageAction; import com.linecorp.bot.model.action.PostbackAction; import com.linecorp.bot.model.action.URIAction; import com.linecorp.bot.model.event.BeaconEvent; import com.linecorp.bot.model.event.Event; import com.linecorp.bot.model.event.FollowEvent; import com.linecorp.bot.model.event.JoinEvent; import com.linecorp.bot.model.event.MessageEvent; import com.linecorp.bot.model.event.PostbackEvent; import com.linecorp.bot.model.event.UnfollowEvent; import com.linecorp.bot.model.event.message.AudioMessageContent; import com.linecorp.bot.model.event.message.ImageMessageContent; import com.linecorp.bot.model.event.message.LocationMessageContent; import com.linecorp.bot.model.event.message.StickerMessageContent; import com.linecorp.bot.model.event.message.TextMessageContent; import com.linecorp.bot.model.event.message.VideoMessageContent; import com.linecorp.bot.model.event.source.GroupSource; import com.linecorp.bot.model.event.source.RoomSource; import com.linecorp.bot.model.event.source.Source; import com.linecorp.bot.model.message.AudioMessage; import com.linecorp.bot.model.message.ImageMessage; import com.linecorp.bot.model.message.ImagemapMessage; import com.linecorp.bot.model.message.LocationMessage; import com.linecorp.bot.model.message.Message; import com.linecorp.bot.model.message.StickerMessage; import com.linecorp.bot.model.message.TemplateMessage; import com.linecorp.bot.model.message.TextMessage; import com.linecorp.bot.model.message.VideoMessage; import com.linecorp.bot.model.message.imagemap.ImagemapArea; import com.linecorp.bot.model.message.imagemap.ImagemapBaseSize; import com.linecorp.bot.model.message.imagemap.MessageImagemapAction; import com.linecorp.bot.model.message.imagemap.URIImagemapAction; import com.linecorp.bot.model.message.template.ButtonsTemplate; import com.linecorp.bot.model.message.template.CarouselColumn; import com.linecorp.bot.model.message.template.CarouselTemplate; import com.linecorp.bot.model.message.template.ConfirmTemplate; import com.linecorp.bot.model.profile.UserProfileResponse; import com.linecorp.bot.model.response.BotApiResponse; import com.linecorp.bot.spring.boot.annotation.EventMapping; import com.linecorp.bot.spring.boot.annotation.LineMessageHandler; import lombok.NonNull; import lombok.Value; import lombok.extern.slf4j.Slf4j; @Slf4j @LineMessageHandler @RestController public class KitchenSinkController { @Autowired private LineMessagingClient lineMessagingClient; private String TokenCallback1; @EventMapping public void handleTextMessageEvent(MessageEvent<TextMessageContent> event) throws Exception { TextMessageContent message = event.getMessage(); handleTextContent(event.getReplyToken(), event, message); } @EventMapping public void handleStickerMessageEvent(MessageEvent<StickerMessageContent> event) { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleLocationMessageEvent(MessageEvent<LocationMessageContent> event) { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleImageMessageEvent(MessageEvent<ImageMessageContent> event) throws IOException { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleAudioMessageEvent(MessageEvent<AudioMessageContent> event) throws IOException { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleVideoMessageEvent(MessageEvent<VideoMessageContent> event) throws IOException { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleUnfollowEvent(UnfollowEvent event) { log.info("unfollowed this bot: {}", event); } @EventMapping public void handleFollowEvent(FollowEvent event) { String replyToken = event.getReplyToken(); this.replyText(replyToken, "bot telah di ikuti info lebih lanjut /help"); } @EventMapping public void handleJoinEvent(JoinEvent event) { String replyToken = event.getReplyToken(); this.replyText(replyToken, "Bot telah bergabung ke grup info lebih lanjut /help" ); } @EventMapping public void handlePostbackEvent(PostbackEvent event) { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleBeaconEvent(BeaconEvent event) { log.info("Received message(Ignored): {}", event); } @EventMapping public void handleOtherEvent(Event event) { log.info("Received message(Ignored): {}", event); } private void reply(@NonNull String replyToken, @NonNull Message message) { reply(replyToken, Collections.singletonList(message)); } private void reply(@NonNull String replyToken, @NonNull List<Message> messages) { try { BotApiResponse apiResponse = lineMessagingClient .replyMessage(new ReplyMessage(replyToken, messages)) .get(); log.info("Sent messages: {}", apiResponse); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } private void replyText(@NonNull String replyToken, @NonNull String message) { if (replyToken.isEmpty()) { throw new IllegalArgumentException("replyToken must not be empty"); } if (message.length() > 1000) { message = message.substring(0, 1000 - 2); } this.reply(replyToken, new TextMessage(message)); } private void push(@NonNull String To, @NonNull Message message) { push(To, Collections.singletonList(message)); } private void push(@NonNull String To, @NonNull List<Message> messages) { try { BotApiResponse apiResponse = lineMessagingClient .pushMessage(new PushMessage(To, messages)) .get(); log.info("Sent messages: {}", apiResponse); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } private void pushText(@NonNull String To, @NonNull String message) { if (To.isEmpty()) { throw new IllegalArgumentException("replyToken must not be empty"); } if (message.length() > 1000) { message = message.substring(0, 1000 - 2); } this.push(To, new TextMessage(message)); } private Timer startTimer() { Timer timer =new Timer(); return timer; } private String DB1(Connection connection){ String Messages; try{ Statement stmt = connection.createStatement(); stmt.executeUpdate("DROP TABLE IF EXISTS ticks"); stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now() + INTERVAL '7 HOUR')"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); while (rs.next()) { Messages = "Waktu Indonesia Barat: " + rs.getTimestamp("tick"); } }catch(SQLException e){ Messages = e.getMessage(); } return Messages; } private void handleTextContent(String replyToken, Event event, TextMessageContent content) throws Exception { Timer t0; String text = content.getText(); Connection connection = getConnection(); log.info("Got text message from {}: {}", replyToken, text); if (text.indexOf("/create")>=0){ String userId = event.getSource().getUserId(); if (userId != null) { lineMessagingClient .getProfile(userId) .whenComplete((profile, throwable) -> { if (throwable != null) { this.replyText(replyToken, throwable.getMessage()); return; } this.reply( replyToken, Arrays.asList(new TextMessage( "Id: " + userId), new TextMessage( "Display name: " + profile.getDisplayName()), new TextMessage( "Status message: " + profile.getStatusMessage())) ); }); } else { this.replyText(replyToken, "Tolong izinkan Bot mengakses akun"); } }else if (text.indexOf("/join")>=0){ String imageUrl = createUri("/static/buttons/1040.jpg"); ButtonsTemplate buttonsTemplate = new ButtonsTemplate( imageUrl, "My button sample", "Hello, my button", Arrays.asList( new URIAction("Go to line.me", "https://line.me"), new PostbackAction("Say hello1", DB1(connection)), new PostbackAction("hello2", "hello", "hello"), new MessageAction("Say message", "Rice") )); TemplateMessage templateMessage = new TemplateMessage("Button alt text", buttonsTemplate); this.reply(replyToken, templateMessage); }else if (text.indexOf("/start")>=0){ String imageUrl = createUri("/static/buttons/1040.jpg"); ButtonsTemplate buttonsTemplate = new ButtonsTemplate( imageUrl, "My button sample", "Hello, my button", Arrays.asList( new URIAction("Go to line.me", "https://line.me"), new PostbackAction("Say hello1", "hello"), new PostbackAction("hello2", "hello", "hello"), new MessageAction("Say message", "Rice") )); TemplateMessage templateMessage = new TemplateMessage("Button alt text", buttonsTemplate); this.reply(replyToken, templateMessage); }else if(text.indexOf("/time")>=0){ try{ Statement stmt = connection.createStatement(); stmt.executeUpdate("DROP TABLE IF EXISTS ticks"); stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now() + INTERVAL '7 HOUR')"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); while (rs.next()) { this.replyText(replyToken,"Waktu Indonesia Barat: " + rs.getTimestamp("tick")); } }catch(SQLException e){ this.replyText(replyToken,e.getMessage()); } }else if(text.indexOf("/delay")>=0){ Source source = event.getSource(); String id=""; this.TokenCallback1 = replyToken; if (source instanceof GroupSource) { id = ((GroupSource) source).getGroupId(); } if (id ==""){ id = event.getSource().getUserId(); } t0 = startTimer(); t0.schedule( new TimerTask() { @Override public void run() { try{ Connection connection = KitchenSinkController.getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("DROP TABLE IF EXISTS ticks"); stmt.executeUpdate("CREATE TABLE ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now() + INTERVAL '7 HOUR')"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); while (rs.next()) { KitchenSinkController.this.replyText(KitchenSinkController.this.TokenCallback1,"Read from DB: " + rs.getTimestamp("tick")); } }catch(SQLException e){ KitchenSinkController.this.replyText(KitchenSinkController.this.TokenCallback1,e.getMessage()); }catch(URISyntaxException err){ KitchenSinkController.this.replyText(KitchenSinkController.this.TokenCallback1,err.getMessage()); } t0.cancel(); } }, 5000, 100); // Every second }else if (text.indexOf("/help")>=0){ this.replyText(replyToken, "feature /help : bantuan\n"+"/imagemap:gambar yang dapat diklik\n"+"/buttons:tombol\n"+ "/question:pertanyaan\n"+"/carousel:carousel\n"+"/leave:keluar dari grup\n"+"/profile:user ID\n"); }else if (text.indexOf("/leave")>=0){ Source source = event.getSource(); if (source instanceof GroupSource) { this.replyText(replyToken, "Bot meninggalkan grup"); lineMessagingClient.leaveGroup(((GroupSource) source).getGroupId()).get(); } else if (source instanceof RoomSource) { this.replyText(replyToken, "Bot meninggalkan ruangan"); lineMessagingClient.leaveRoom(((RoomSource) source).getRoomId()).get(); } else { this.replyText(replyToken, "ini room 1:1 tidak bisa menggunakan perintah /leave"); } }else{ log.info("Ignore message {}: {}", replyToken, text); } } private static Connection getConnection() throws URISyntaxException, SQLException { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath(); return DriverManager.getConnection(dbUrl, username, password); } private static String createUri(String path) { return ServletUriComponentsBuilder.fromCurrentContextPath() .path(path).build() .toUriString(); } private void system(String... args) { ProcessBuilder processBuilder = new ProcessBuilder(args); try { Process start = processBuilder.start(); int i = start.waitFor(); log.info("result: {} => {}", Arrays.toString(args), i); } catch (IOException e) { throw new UncheckedIOException(e); } catch (InterruptedException e) { log.info("Interrupted", e); Thread.currentThread().interrupt(); } } private static DownloadedContent saveContent(String ext, MessageContentResponse responseBody) { log.info("Got content-type: {}", responseBody); DownloadedContent tempFile = createTempFile(ext); try (OutputStream outputStream = Files.newOutputStream(tempFile.path)) { ByteStreams.copy(responseBody.getStream(), outputStream); log.info("Saved {}: {}", ext, tempFile); return tempFile; } catch (IOException e) { throw new UncheckedIOException(e); } } private static DownloadedContent createTempFile(String ext) { String fileName = LocalDateTime.now().toString() + '-' + UUID.randomUUID().toString() + '.' + ext; Path tempFile = KitchenSinkApplication.downloadedContentDir.resolve(fileName); tempFile.toFile().deleteOnExit(); return new DownloadedContent( tempFile, createUri("/downloaded/" + tempFile.getFileName())); } @Value public static class DownloadedContent { Path path; String uri; } @RequestMapping("/greeting") public Greeting greeting(@RequestParam(value="UserId", defaultValue="") String User,@RequestParam(value="message", defaultValue="") String message) { this.pushText(User, message); return new Greeting(User,message); } }
add existing files
sample-spring-boot-kitchensink/src/main/java/com/example/bot/spring/KitchenSinkController.java
add existing files
<ide><path>ample-spring-boot-kitchensink/src/main/java/com/example/bot/spring/KitchenSinkController.java <ide> return timer; <ide> } <ide> private String DB1(Connection connection){ <del> String Messages; <add> String Messages=""; <ide> try{ <ide> Statement stmt = connection.createStatement(); <ide> stmt.executeUpdate("DROP TABLE IF EXISTS ticks");
JavaScript
mit
d43260923fcd14599cc6b8ca7030af753ef68ace
0
HR/Crypter,HR/Crypter,HR/Crypter
'use strict' const electron = require('electron') const app = electron.app const BrowserWindow = electron.BrowserWindow const ipc = electron.ipcMain const dialog = electron.dialog const crypto = require('./src/crypto') const Db = require('./src/Db') const MasterPass = require('./src/MasterPass') const MasterPassKey = require('./src/MasterPassKey') const _ = require('lodash') // adds debug features like hotkeys for triggering dev tools and reload require('electron-debug')() // declare global constants global.creds = {} global.paths = { mdb: `${app.getPath('userData')}/mdb`, userData: app.getPath('userData'), home: app.getPath('home'), documents: app.getPath('documents') } global.views = { masterpassprompt: `file://${__dirname}/static/masterpassprompt.html`, setup: `file://${__dirname}/static/setup.html`, crypter: `file://${__dirname}/static/crypter.html` } const logger = require('./script/logger') // change exec path logger.info(`AppPath: ${app.getAppPath()}`) logger.info(`UseData Path: ${app.getPath('userData')}`) process.chdir(app.getAppPath()) logger.info(`Changed cwd to: ${process.cwd()}`) logger.info(`Electron node v${process.versions.node}`) /** * Promisification of initialisation **/ const init = function () { return new Promise(function (resolve, reject) { // initialise mdb global.mdb = new Db(global.paths.mdb) logger.info(`status: ${global.mdb._status}`) // Get the credentials serialized object from mdb // Resolves with false if not found // setTimeout to ensure mdb is open before get creds setTimeout(function () { resolve(global.mdb.onlyGetValue('creds')) }, 1000) }) } const initMain = function () { logger.verbose(`PROMISE: Main initialisation`) return new Promise(function (resolve, reject) { // restore the creds object globally resolve(global.mdb.restoreGlobalObj('creds')) }) } const closeDb = function () { if (_.isEmpty(global.mdb) ? false : global.mdb.isOpen()) { // close mdb before quitting if opened global.mdb.close() } } /** * Event handlers **/ // Main event handler app.on('ready', function () { // Check synchronously whether paths exist init() .then((mainRun) => { logger.info(`Init done.`) // If the credentials not find in mdb, run setup // otherwise run main if (mainRun) { // Run main logger.info(`Main run. Creating CrypterWindow...`) // Initialise (open mdb and get creds) initMain() .then(() => { // Obtain MasterPass, derive MasterPassKey and set globally return masterPassPromptWindow() }) .then(() => { // Create the Crypter window and open it return crypterWindow() }) .then(() => { // Quit app after crypterWindow is closed app.quit() }) .catch(function (error) { // Catch any fatal errors and exit logger.error(`PROMISE ERR: ${error.stack}`) // dialog.showErrorBox('Oops, we encountered a problem...', error.message) app.quit() }) } else { // Run Setup logger.info('Setup run. Creating Setup wizard...') setupWindow() .then(() => { logger.info('MAIN Setup successfully completed. quitting...') // setup successfully completed app.quit() }) .catch(function (error) { logger.error(`PROMISE ERR: ${error.stack}`) // Display error to user dialog.showErrorBox('Oops, we encountered a problem...', error.message) app.quit() }) } }) .catch(function (error) { logger.error(`PROMISE ERR: ${error.stack}`) // Display error to user dialog.showErrorBox('Oops, we encountered a problem...', error.message) app.quit() }) }) app.on('window-all-closed', () => { logger.verbose('APP: window-all-closed event emitted') // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q }) app.on('quit', () => { logger.info('APP: quit event emitted') closeDb() }) app.on('will-quit', (event) => { // will exit program once exit procedures have been run (exit flag is true) logger.info(`APP.ON('will-quit'): will-quit event emitted`) closeDb() }) /** * Promisification of windows **/ // Creates the crypter window let crypterWindow = function () { return new Promise(function (resolve, reject) { CrypterWindow(function () { resolve() }) }) } // Creates the setup window let setupWindow = function () { return new Promise(function (resolve, reject) { SetupWindow(function (err) { if (err) { reject(err) } else { resolve() } }) }) } // Creates the MasterPassPrompt window let masterPassPromptWindow = function () { return new Promise(function (resolve, reject) { MasterPassPromptWindow(function (err, gotMP) { if (err) reject(err) if (gotMP) { resolve() } else { reject(new Error('Could not get MasterPass')) } }) }) } /** * Controller functions (windows) **/ function CrypterWindow (callback) { // creates a new BrowserWindow let win = new BrowserWindow({ width: 350, height: 450, center: true, show: true, titleBarStyle: 'hidden-inset', resizable: false, movable: true }) let webContents = win.webContents // loads crypt.html view into the BrowserWindow win.loadURL(global.views.crypter) // When user selects a file to encrypt in Crypter window ipc.on('cryptFile', function (event, filePath) { logger.verbose('IPCMAIN: cryptFile emitted. Starting encryption...') crypto.crypt(filePath, global.MasterPassKey.get()) .then((file) => { webContents.send('cryptedFile', file) }) .catch((err) => { logger.info(`cryptFile error`) logger.error(err) webContents.send('cryptErr', err) }) }) // When user selects a file to decrypt in Crypter window ipc.on('decryptFile', function (event, filePath) { logger.verbose('IPCMAIN: decryptFile emitted. Starting decryption...') // let destPath = filePath.replace('.crypto', '.decrypto') crypto.decrypt(filePath, global.MasterPassKey.get()) .then((file) => { logger.info('decrypted') webContents.send('decryptedFile', file) }) .catch((err) => { logger.info(`decryptFile error`) logger.error(err) webContents.send('cryptErr', err.message) }) }) win.on('closed', function () { logger.info('win.closed event emitted for PromptWindow') win = null callback() }) return win } function SetupWindow (callback) { // setup view controller // creates the setup window let win = new BrowserWindow({ width: 600, height: 400, center: true, show: true, titleBarStyle: 'hidden-inset', resizable: false, movable: true }) let webContents = win.webContents let error // loads setup.html view into the SetupWindow win.loadURL(global.views.setup) ipc.on('setMasterPass', function (event, masterpass) { // setMasterPass event triggered by render proces logger.verbose('IPCMAIN: setMasterPass emitted Setting Masterpass...') // derive MasterPassKey, genPassHash and set creds globally MasterPass.set(masterpass) .then((mpkey) => { // set the derived MasterPassKey globally global.MasterPassKey = new MasterPassKey(mpkey) return }) .then(() => { // save the credentials used to derive the MasterPassKey return global.mdb.saveGlobalObj('creds') }) .then(() => { // Inform user that the MasterPass has successfully been set webContents.send('setMasterPassResult', null) }) .catch((err) => { // Inform user of the error that occured while setting the MasterPass webContents.send('setMasterPassResult', err) error = err }) }) ipc.on('done', function (event, masterpass) { // Dond event emotted from render process logger.info('IPCMAIN: done emitted setup complete. Closing...') // Setup successfully finished // therefore set error to nothing error = null // Upgrade to electron >= v1.2.2 // app.relaunch({args: process.argv.slice(1).concat(['--relaunch'])}) // app.exit(0) // close window (invokes 'closed') event win.close() }) win.on('closed', function () { logger.verbose('IPCMAIN: win.closed event emitted for setupWindow.') // close window by setting it to nothing (null) win = null // if error occured then send error back to callee else send null callback((error) ? error : null) }) } // exporting window to be used in MasterPass module function MasterPassPromptWindow (callback) { let gotMP = false // init gotMP flag with false let error = null const CLOSE_TIMEOUT = 2000 // creates a new BrowserWindow let win = new BrowserWindow({ width: 300, height: 450, center: true, show: true, titleBarStyle: 'hidden-inset', resizable: false, movable: true }) let webContents = win.webContents // loads masterpassprompt.html view into the BrowserWindow win.loadURL(global.views.masterpassprompt) ipc.on('checkMasterPass', function (event, masterpass) { logger.verbose('IPCMAIN: checkMasterPass emitted. Checking MasterPass...') // Check user submitted MasterPass MasterPass.check(masterpass) .then((res) => { if (res.match) { // Password matches logger.info('IPCMAIN: PASSWORD MATCHES!') // Save MasterPassKey (while program is running) global.MasterPassKey = new MasterPassKey(res.key) // send result match result to masterpassprompt.html webContents.send('checkMasterPassResult', { err: null, match: res.match }) gotMP = true // Close after 1 second setTimeout(function () { // close window (invokes 'closed') event win.close() }, CLOSE_TIMEOUT) } else { logger.warn('IPCMAIN: PASSWORD DOES NOT MATCH!') webContents.send('checkMasterPassResult', { err: null, match: res.match }) } }) .catch((err) => { // Inform user of error (on render side) webContents.send('checkMasterPassResult', err) // set error error = err // Close after 1 second setTimeout(function () { // close window (invokes 'closed') event win.close() }, CLOSE_TIMEOUT) }) }) ipc.on('setMasterPass', function (event, masterpass) { // setMasterPass event triggered by render proces logger.verbose('IPCMAIN: setMasterPass emitted Setting Masterpass...') // derive MasterPassKey, genPassHash and set creds globally MasterPass.set(masterpass) .then((mpkey) => { // set the derived MasterPassKey globally global.MasterPassKey = new MasterPassKey(mpkey) return }) .then(() => { // save the credentials used to derive the MasterPassKey return global.mdb.saveGlobalObj('creds') }) .then(() => { // Inform user that the MasterPass has successfully been set logger.verbose('IPCMAIN: Masterpass has been reset successfully') webContents.send('setMasterPassResult', null) }) .catch((err) => { // Inform user of the error that occured while setting the MasterPass webContents.send('setMasterPassResult', err) error = err }) }) win.on('closed', function () { logger.info('win.closed event emitted for PromptWindow') // send error and gotMP back to callee (masterPassPromptWindow Promise) callback(error, gotMP) // close window by setting it to nothing (null) win = null }) return win }
app/index.js
'use strict' const electron = require('electron') const app = electron.app const BrowserWindow = electron.BrowserWindow const ipc = electron.ipcMain const dialog = electron.dialog const crypto = require('./src/crypto') const Db = require('./src/Db') const MasterPass = require('./src/MasterPass') const MasterPassKey = require('./src/MasterPassKey') const _ = require('lodash') // adds debug features like hotkeys for triggering dev tools and reload require('electron-debug')() // declare global constants global.creds = {} global.paths = { mdb: `${app.getPath('userData')}/mdb`, userData: app.getPath('userData'), home: app.getPath('home'), documents: app.getPath('documents') } global.views = { masterpassprompt: `file://${__dirname}/static/masterpassprompt.html`, setup: `file://${__dirname}/static/setup.html`, crypter: `file://${__dirname}/static/crypter.html` } const logger = require('./script/logger') // change exec path logger.info(`AppPath: ${app.getAppPath()}`) logger.info(`UseData Path: ${app.getPath('userData')}`) process.chdir(app.getAppPath()) logger.info(`Changed cwd to: ${process.cwd()}`) logger.info(`Electron node v${process.versions.node}`) /** * Promisification of initialisation **/ const init = function () { return new Promise(function (resolve, reject) { // initialise mdb global.mdb = new Db(global.paths.mdb) logger.info(`status: ${global.mdb._status}`) // Get the credentials serialized object from mdb // Resolves with false if not found // setTimeout to ensure mdb is open before get creds setTimeout(function () { resolve(global.mdb.onlyGetValue('creds')) }, 1000) }) } const initMain = function () { logger.verbose(`PROMISE: Main initialisation`) return new Promise(function (resolve, reject) { // restore the creds object globally resolve(global.mdb.restoreGlobalObj('creds')) }) } const closeDb = function () { if (_.isEmpty(global.mdb) ? false : global.mdb.isOpen()) { // close mdb before quitting if opened global.mdb.close() } } /** * Event handlers **/ // Main event handler app.on('ready', function () { // Check synchronously whether paths exist init() .then((mainRun) => { logger.info(`Init done.`) // If the credentials not find in mdb, run setup // otherwise run main if (mainRun) { // Run main logger.info(`Main run. Creating CrypterWindow...`) // Initialise (open mdb and get creds) initMain() .then(() => { // Obtain MasterPass, derive MasterPassKey and set globally return masterPassPromptWindow() }) .then(() => { // Create the Crypter window and open it return crypterWindow() }) .then(() => { // Quit app after crypterWindow is closed app.quit() }) .catch(function (error) { // Catch any fatal errors and exit logger.error(`PROMISE ERR: ${error.stack}`) // dialog.showErrorBox('Oops, we encountered a problem...', error.message) app.quit() }) } else { // Run Setup logger.info('Setup run. Creating Setup wizard...') setupWindow() .then(() => { logger.info('MAIN Setup successfully completed. quitting...') // setup successfully completed app.quit() }) .catch(function (error) { logger.error(`PROMISE ERR: ${error.stack}`) // Display error to user dialog.showErrorBox('Oops, we encountered a problem...', error.message) app.quit() }) } }) .catch(function (error) { logger.error(`PROMISE ERR: ${error.stack}`) // Display error to user dialog.showErrorBox('Oops, we encountered a problem...', error.message) app.quit() }) }) app.on('window-all-closed', () => { logger.verbose('APP: window-all-closed event emitted') // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() } }) app.on('quit', () => { logger.info('APP: quit event emitted') closeDb() }) app.on('will-quit', (event) => { // will exit program once exit procedures have been run (exit flag is true) logger.info(`APP.ON('will-quit'): will-quit event emitted`) closeDb() }) /** * Promisification of windows **/ // Creates the crypter window let crypterWindow = function () { return new Promise(function (resolve, reject) { CrypterWindow(function () { resolve() }) }) } // Creates the setup window let setupWindow = function () { return new Promise(function (resolve, reject) { SetupWindow(function (err) { if (err) { reject(err) } else { resolve() } }) }) } // Creates the MasterPassPrompt window let masterPassPromptWindow = function () { return new Promise(function (resolve, reject) { MasterPassPromptWindow(function (err, gotMP) { if (err) reject(err) if (gotMP) { resolve() } else { reject(new Error('Could not get MasterPass')) } }) }) } /** * Controller functions (windows) **/ function CrypterWindow (callback) { // creates a new BrowserWindow let win = new BrowserWindow({ width: 350, height: 450, center: true, show: true, titleBarStyle: 'hidden-inset', resizable: false, movable: true }) let webContents = win.webContents // loads crypt.html view into the BrowserWindow win.loadURL(global.views.crypter) // When user selects a file to encrypt in Crypter window ipc.on('cryptFile', function (event, filePath) { logger.verbose('IPCMAIN: cryptFile emitted. Starting encryption...') crypto.crypt(filePath, global.MasterPassKey.get()) .then((file) => { webContents.send('cryptedFile', file) }) .catch((err) => { logger.info(`cryptFile error`) logger.error(err) webContents.send('cryptErr', err) }) }) // When user selects a file to decrypt in Crypter window ipc.on('decryptFile', function (event, filePath) { logger.verbose('IPCMAIN: decryptFile emitted. Starting decryption...') // let destPath = filePath.replace('.crypto', '.decrypto') crypto.decrypt(filePath, global.MasterPassKey.get()) .then((file) => { logger.info('decrypted') webContents.send('decryptedFile', file) }) .catch((err) => { logger.info(`decryptFile error`) logger.error(err) webContents.send('cryptErr', err.message) }) }) win.on('closed', function () { logger.info('win.closed event emitted for PromptWindow') win = null callback() }) return win } function SetupWindow (callback) { // setup view controller // creates the setup window let win = new BrowserWindow({ width: 600, height: 400, center: true, show: true, titleBarStyle: 'hidden-inset', resizable: false, movable: true }) let webContents = win.webContents let error // loads setup.html view into the SetupWindow win.loadURL(global.views.setup) ipc.on('setMasterPass', function (event, masterpass) { // setMasterPass event triggered by render proces logger.verbose('IPCMAIN: setMasterPass emitted Setting Masterpass...') // derive MasterPassKey, genPassHash and set creds globally MasterPass.set(masterpass) .then((mpkey) => { // set the derived MasterPassKey globally global.MasterPassKey = new MasterPassKey(mpkey) return }) .then(() => { // save the credentials used to derive the MasterPassKey return global.mdb.saveGlobalObj('creds') }) .then(() => { // Inform user that the MasterPass has successfully been set webContents.send('setMasterPassResult', null) }) .catch((err) => { // Inform user of the error that occured while setting the MasterPass webContents.send('setMasterPassResult', err) error = err }) }) ipc.on('done', function (event, masterpass) { // Dond event emotted from render process logger.info('IPCMAIN: done emitted setup complete. Closing...') // Setup successfully finished // therefore set error to nothing error = null // Upgrade to electron >= v1.2.2 // app.relaunch({args: process.argv.slice(1).concat(['--relaunch'])}) // app.exit(0) // close window (invokes 'closed') event win.close() }) win.on('closed', function () { logger.verbose('IPCMAIN: win.closed event emitted for setupWindow.') // close window by setting it to nothing (null) win = null // if error occured then send error back to callee else send null callback((error) ? error : null) }) } // exporting window to be used in MasterPass module function MasterPassPromptWindow (callback) { let gotMP = false // init gotMP flag with false let error = null const CLOSE_TIMEOUT = 2000 // creates a new BrowserWindow let win = new BrowserWindow({ width: 300, height: 450, center: true, show: true, titleBarStyle: 'hidden-inset', resizable: false, movable: true }) let webContents = win.webContents // loads masterpassprompt.html view into the BrowserWindow win.loadURL(global.views.masterpassprompt) ipc.on('checkMasterPass', function (event, masterpass) { logger.verbose('IPCMAIN: checkMasterPass emitted. Checking MasterPass...') // Check user submitted MasterPass MasterPass.check(masterpass) .then((res) => { if (res.match) { // Password matches logger.info('IPCMAIN: PASSWORD MATCHES!') // Save MasterPassKey (while program is running) global.MasterPassKey = new MasterPassKey(res.key) // send result match result to masterpassprompt.html webContents.send('checkMasterPassResult', { err: null, match: res.match }) gotMP = true // Close after 1 second setTimeout(function () { // close window (invokes 'closed') event win.close() }, CLOSE_TIMEOUT) } else { logger.warn('IPCMAIN: PASSWORD DOES NOT MATCH!') webContents.send('checkMasterPassResult', { err: null, match: res.match }) } }) .catch((err) => { // Inform user of error (on render side) webContents.send('checkMasterPassResult', err) // set error error = err // Close after 1 second setTimeout(function () { // close window (invokes 'closed') event win.close() }, CLOSE_TIMEOUT) }) }) ipc.on('setMasterPass', function (event, masterpass) { // setMasterPass event triggered by render proces logger.verbose('IPCMAIN: setMasterPass emitted Setting Masterpass...') // derive MasterPassKey, genPassHash and set creds globally MasterPass.set(masterpass) .then((mpkey) => { // set the derived MasterPassKey globally global.MasterPassKey = new MasterPassKey(mpkey) return }) .then(() => { // save the credentials used to derive the MasterPassKey return global.mdb.saveGlobalObj('creds') }) .then(() => { // Inform user that the MasterPass has successfully been set logger.verbose('IPCMAIN: Masterpass has been reset successfully') webContents.send('setMasterPassResult', null) }) .catch((err) => { // Inform user of the error that occured while setting the MasterPass webContents.send('setMasterPassResult', err) error = err }) }) win.on('closed', function () { logger.info('win.closed event emitted for PromptWindow') // send error and gotMP back to callee (masterPassPromptWindow Promise) callback(error, gotMP) // close window by setting it to nothing (null) win = null }) return win }
Try to fix #16
app/index.js
Try to fix #16
<ide><path>pp/index.js <ide> logger.verbose('APP: window-all-closed event emitted') <ide> // On macOS it is common for applications and their menu bar <ide> // to stay active until the user quits explicitly with Cmd + Q <del> if (process.platform !== 'darwin') { <del> app.quit() <del> } <ide> }) <ide> <ide> app.on('quit', () => {
JavaScript
mit
be51593f71750ec4fbbaefb679949fc0ab5d8e78
0
leader22/cgmd-editor,leader22/cgmd-editor
import dispatcher from './dispatcher'; const Creator = { updateMd: (md) => { const action = { type: 'UPDATE_MD', data: { md } }; dispatcher.dispatch(action); } }; export default Creator;
src/script/action-creator.js
import dispatcher from '../dispatcher'; const Creator = { updateMd: (md) => { const action = { type: 'UPDATE_MD', data: { md } }; dispatcher.dispatch(action); } }; export default Creator;
fix typo
src/script/action-creator.js
fix typo
<ide><path>rc/script/action-creator.js <del>import dispatcher from '../dispatcher'; <add>import dispatcher from './dispatcher'; <ide> <ide> const Creator = { <ide> updateMd: (md) => {
Java
apache-2.0
error: pathspec 'src/main/java/com/github/ansell/stardog/StardogRepositoryManager.java' did not match any file(s) known to git
f89bb90b2ff2cb14fdb81cc93496549e4b710589
1
ansell/sesame-stardog-manager,ansell/sesame-stardog-manager
/** * */ package com.github.ansell.stardog; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.config.RepositoryConfig; import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.manager.RepositoryInfo; import org.openrdf.repository.manager.RepositoryManager; import com.complexible.stardog.StardogException; import com.complexible.stardog.api.ConnectionConfiguration; import com.complexible.stardog.api.admin.AdminConnection; import com.complexible.stardog.api.admin.AdminConnectionConfiguration; import com.complexible.stardog.sesame.StardogRepository; /** * * * @author Peter Ansell [email protected] */ public class StardogRepositoryManager extends RepositoryManager { private AdminConnectionConfiguration adminConn; private ConnectionConfiguration connConn; public StardogRepositoryManager(AdminConnectionConfiguration adminConn, ConnectionConfiguration connConn) { super(new ConcurrentHashMap<String, Repository>()); this.adminConn = adminConn; this.connConn = connConn; } @Override protected Repository createSystemRepository() throws RepositoryException { Repository aRepo = new StardogRepository(connConn.copy().database("SYSTEM")); aRepo.initialize(); return aRepo; } @Override protected Repository createRepository(String id) throws RepositoryConfigException, RepositoryException { try { Collection<String> list = adminConn.connect().list(); for(String nextRepo : list) { if(nextRepo.equals(id)) { Repository aRepo = new StardogRepository(connConn.copy().database(id)); aRepo.initialize(); return aRepo; } } return null; } catch(StardogException e) { throw new RepositoryException(e); } } @Override public RepositoryInfo getRepositoryInfo(String id) throws RepositoryException { try { Collection<String> list = adminConn.connect().list(); for(String nextRepo : list) { if(nextRepo.equals(id)) { RepositoryInfo result = new RepositoryInfo(); result.setId(id); result.setDescription(id); // TODO: How do we know what URL adminConn/connConn are using from their public // methods? // result.setLocation(url); return result; } } return null; } catch(StardogException e) { throw new RepositoryException(e); } } @Override public Collection<RepositoryInfo> getAllRepositoryInfos(boolean skipSystemRepo) throws RepositoryException { try { Collection<String> list = adminConn.connect().list(); Collection<RepositoryInfo> result = new ArrayList<RepositoryInfo>(list.size()); for(String nextRepo : list) { if(!skipSystemRepo || !(skipSystemRepo && nextRepo.equals("SYSTEM"))) { RepositoryInfo nextResult = new RepositoryInfo(); nextResult.setId(nextRepo); nextResult.setDescription(nextRepo); // TODO: How do we know what URL adminConn/connConn are using from their public // methods? // result.setLocation(url); } } return result; } catch(StardogException e) { throw new RepositoryException(e); } } @Override protected void cleanUpRepository(String repositoryID) throws IOException { // TODO Auto-generated method stub } @Override public URL getLocation() throws MalformedURLException { // TODO Auto-generated method stub return null; } }
src/main/java/com/github/ansell/stardog/StardogRepositoryManager.java
Initial stubbing of StardogRepositoryManager
src/main/java/com/github/ansell/stardog/StardogRepositoryManager.java
Initial stubbing of StardogRepositoryManager
<ide><path>rc/main/java/com/github/ansell/stardog/StardogRepositoryManager.java <add>/** <add> * <add> */ <add>package com.github.ansell.stardog; <add> <add>import java.io.IOException; <add>import java.net.MalformedURLException; <add>import java.net.URL; <add>import java.util.ArrayList; <add>import java.util.Collection; <add>import java.util.Map; <add>import java.util.Set; <add>import java.util.concurrent.ConcurrentHashMap; <add> <add>import org.openrdf.repository.Repository; <add>import org.openrdf.repository.RepositoryException; <add>import org.openrdf.repository.config.RepositoryConfig; <add>import org.openrdf.repository.config.RepositoryConfigException; <add>import org.openrdf.repository.manager.RepositoryInfo; <add>import org.openrdf.repository.manager.RepositoryManager; <add> <add>import com.complexible.stardog.StardogException; <add>import com.complexible.stardog.api.ConnectionConfiguration; <add>import com.complexible.stardog.api.admin.AdminConnection; <add>import com.complexible.stardog.api.admin.AdminConnectionConfiguration; <add>import com.complexible.stardog.sesame.StardogRepository; <add> <add>/** <add> * <add> * <add> * @author Peter Ansell [email protected] <add> */ <add>public class StardogRepositoryManager extends RepositoryManager <add>{ <add> private AdminConnectionConfiguration adminConn; <add> private ConnectionConfiguration connConn; <add> <add> public StardogRepositoryManager(AdminConnectionConfiguration adminConn, ConnectionConfiguration connConn) <add> { <add> super(new ConcurrentHashMap<String, Repository>()); <add> this.adminConn = adminConn; <add> this.connConn = connConn; <add> } <add> <add> @Override <add> protected Repository createSystemRepository() throws RepositoryException <add> { <add> Repository aRepo = new StardogRepository(connConn.copy().database("SYSTEM")); <add> aRepo.initialize(); <add> return aRepo; <add> } <add> <add> @Override <add> protected Repository createRepository(String id) throws RepositoryConfigException, RepositoryException <add> { <add> try <add> { <add> Collection<String> list = adminConn.connect().list(); <add> <add> for(String nextRepo : list) <add> { <add> if(nextRepo.equals(id)) <add> { <add> Repository aRepo = new StardogRepository(connConn.copy().database(id)); <add> aRepo.initialize(); <add> return aRepo; <add> } <add> } <add> <add> return null; <add> } <add> catch(StardogException e) <add> { <add> throw new RepositoryException(e); <add> } <add> } <add> <add> @Override <add> public RepositoryInfo getRepositoryInfo(String id) throws RepositoryException <add> { <add> try <add> { <add> Collection<String> list = adminConn.connect().list(); <add> <add> for(String nextRepo : list) <add> { <add> if(nextRepo.equals(id)) <add> { <add> RepositoryInfo result = new RepositoryInfo(); <add> result.setId(id); <add> result.setDescription(id); <add> // TODO: How do we know what URL adminConn/connConn are using from their public <add> // methods? <add> // result.setLocation(url); <add> return result; <add> } <add> } <add> <add> return null; <add> } <add> catch(StardogException e) <add> { <add> throw new RepositoryException(e); <add> } <add> } <add> <add> @Override <add> public Collection<RepositoryInfo> getAllRepositoryInfos(boolean skipSystemRepo) throws RepositoryException <add> { <add> try <add> { <add> Collection<String> list = adminConn.connect().list(); <add> Collection<RepositoryInfo> result = new ArrayList<RepositoryInfo>(list.size()); <add> <add> for(String nextRepo : list) <add> { <add> if(!skipSystemRepo || !(skipSystemRepo && nextRepo.equals("SYSTEM"))) <add> { <add> RepositoryInfo nextResult = new RepositoryInfo(); <add> nextResult.setId(nextRepo); <add> nextResult.setDescription(nextRepo); <add> // TODO: How do we know what URL adminConn/connConn are using from their public <add> // methods? <add> // result.setLocation(url); <add> } <add> } <add> return result; <add> } <add> catch(StardogException e) <add> { <add> throw new RepositoryException(e); <add> } <add> } <add> <add> @Override <add> protected void cleanUpRepository(String repositoryID) throws IOException <add> { <add> // TODO Auto-generated method stub <add> <add> } <add> <add> @Override <add> public URL getLocation() throws MalformedURLException <add> { <add> // TODO Auto-generated method stub <add> return null; <add> } <add> <add>}
Java
epl-1.0
a4b0ae4f309d67a2ea7588378855a9ef114a9f1d
0
cchabanois/mesfavoris,cchabanois/mesfavoris
package mesfavoris.internal.views; import static mesfavoris.internal.IUIConstants.IMG_UPDATE_BOOKMARK; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.NotEnabledException; import org.eclipse.core.commands.NotHandledException; import org.eclipse.core.commands.common.NotDefinedException; import org.eclipse.core.runtime.IStatus; import org.eclipse.e4.core.services.events.IEventBroker; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.action.IContributionManager; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.fieldassist.FieldDecorationRegistry; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; 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.TreeViewer; import org.eclipse.jface.window.ToolTip; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IMemento; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.FilteredTree; import org.eclipse.ui.dialogs.PatternFilter; import org.eclipse.ui.forms.HyperlinkSettings; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.Form; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.part.DrillDownAdapter; import org.eclipse.ui.part.IShowInSource; import org.eclipse.ui.part.ShowInContext; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.views.properties.IPropertySheetPage; import org.eclipse.ui.views.properties.PropertySheetPage; import org.osgi.service.event.EventHandler; import com.google.common.collect.Lists; import mesfavoris.BookmarksException; import mesfavoris.bookmarktype.IBookmarkPropertiesProvider; import mesfavoris.bookmarktype.IImportTeamProject; import mesfavoris.commons.core.AdapterUtils; import mesfavoris.internal.BookmarksPlugin; import mesfavoris.internal.IUIConstants; import mesfavoris.internal.StatusHelper; import mesfavoris.internal.actions.AddToRemoteBookmarksStoreAction; import mesfavoris.internal.actions.CollapseAllAction; import mesfavoris.internal.actions.ConnectToRemoteBookmarksStoreAction; import mesfavoris.internal.actions.RefreshRemoteFoldersAction; import mesfavoris.internal.actions.RemoveFromRemoteBookmarksStoreAction; import mesfavoris.internal.actions.ToggleLinkAction; import mesfavoris.internal.jobs.ImportTeamProjectFromBookmarkJob; import mesfavoris.internal.numberedbookmarks.NumberedBookmarksVirtualFolder; import mesfavoris.internal.problems.extension.BookmarkProblemHandlers; import mesfavoris.internal.problems.ui.BookmarkProblemsTooltip; import mesfavoris.internal.recent.RecentBookmarksVirtualFolder; import mesfavoris.internal.views.comment.BookmarkCommentArea; import mesfavoris.internal.visited.LatestVisitedBookmarksVirtualFolder; import mesfavoris.internal.visited.MostVisitedBookmarksVirtualFolder; import mesfavoris.model.Bookmark; import mesfavoris.model.BookmarkDatabase; import mesfavoris.model.BookmarkFolder; import mesfavoris.model.BookmarkId; import mesfavoris.model.IBookmarksListener; import mesfavoris.persistence.IBookmarksDirtyStateTracker; import mesfavoris.problems.BookmarkProblem; import mesfavoris.problems.BookmarkProblem.Severity; import mesfavoris.problems.IBookmarkProblemHandler; import mesfavoris.problems.IBookmarkProblems; import mesfavoris.remote.IRemoteBookmarksStore; import mesfavoris.remote.RemoteBookmarksStoreManager; import mesfavoris.topics.BookmarksEvents; public class BookmarksView extends ViewPart { private static final String COMMAND_ID_GOTO_FAVORI = "mesfavoris.command.gotoFavori"; public static final String ID = "mesfavoris.views.BookmarksView"; private final BookmarkDatabase bookmarkDatabase; private final IEventBroker eventBroker; private final RemoteBookmarksStoreManager remoteBookmarksStoreManager; private final IBookmarksDirtyStateTracker bookmarksDirtyStateTracker; private final IBookmarkProblems bookmarkProblems; private final BookmarkProblemHandlers bookmarkProblemHandlers; private final EventHandler bookmarkProblemsEventHandler; private BookmarksTreeViewer bookmarksTreeViewer; private BookmarkCommentArea bookmarkCommentViewer; private DrillDownAdapter drillDownAdapter; private Action refreshAction; private Action collapseAllAction; private ToggleLinkAction toggleLinkAction; private FormToolkit toolkit; private Form form; private IMemento memento; private PreviousActivePartListener previousActivePartListener = new PreviousActivePartListener(); private Composite commentsComposite; private Section commentsSection; private BookmarkProblemsTooltip bookmarkProblemsTooltip; private Image icon; private PropertySheetPage propertyPage; private final IBookmarksListener bookmarksListener = (modifications) -> refreshPropertyPage(); public BookmarksView() { this.bookmarkDatabase = BookmarksPlugin.getDefault().getBookmarkDatabase(); this.eventBroker = (IEventBroker) PlatformUI.getWorkbench().getService(IEventBroker.class); this.remoteBookmarksStoreManager = BookmarksPlugin.getDefault().getRemoteBookmarksStoreManager(); this.bookmarksDirtyStateTracker = BookmarksPlugin.getDefault().getBookmarksDirtyStateTracker(); this.bookmarkProblems = BookmarksPlugin.getDefault().getBookmarkProblems(); this.bookmarkProblemHandlers = BookmarksPlugin.getDefault().getBookmarkProblemHandlers(); bookmarkProblemsEventHandler = (event) -> { refreshPropertyPage(); updateFormBookmarkProblems(bookmarksTreeViewer.getSelectedBookmark()); updateFormToolbar(bookmarksTreeViewer.getSelectedBookmark()); }; } public void createPartControl(Composite parent) { GridLayoutFactory.fillDefaults().applyTo(parent); toolkit = new FormToolkit(parent.getDisplay()); toolkit.getHyperlinkGroup().setHyperlinkUnderlineMode(HyperlinkSettings.UNDERLINE_HOVER); form = toolkit.createForm(parent); icon = BookmarksPlugin.getImageDescriptor(IUIConstants.IMG_BOOKMARKS).createImage(); form.setImage(icon); GridDataFactory.fillDefaults().grab(true, true).applyTo(form); form.setText("Mes Favoris"); toolkit.decorateFormHeading(form); GridLayoutFactory.swtDefaults().applyTo(form.getBody()); SashForm sashForm = new SashForm(form.getBody(), SWT.VERTICAL); toolkit.adapt(sashForm, true, true); GridDataFactory.fillDefaults().grab(true, true).applyTo(sashForm); createTreeControl(sashForm); createCommentsSection(sashForm); makeActions(); hookContextMenu(); contributeToActionBars(); getSite().setSelectionProvider(bookmarksTreeViewer); toggleLinkAction.init(); restoreState(memento); bookmarkDatabase.addListener(bookmarksListener); eventBroker.subscribe(BookmarksEvents.TOPIC_BOOKMARK_PROBLEMS_CHANGED, bookmarkProblemsEventHandler); } private void createCommentsSection(Composite parent) { commentsSection = toolkit.createSection(parent, ExpandableComposite.TITLE_BAR); commentsSection.setText("Comments"); commentsSection.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).create()); commentsComposite = toolkit.createComposite(commentsSection); toolkit.paintBordersFor(commentsComposite); commentsSection.setClient(commentsComposite); GridLayoutFactory.fillDefaults().extendedMargins(2, 2, 2, 2).applyTo(commentsComposite); bookmarkCommentViewer = new BookmarkCommentArea(commentsComposite, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP | toolkit.getBorderStyle(), bookmarkDatabase); bookmarkCommentViewer.getTextWidget().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); GridDataFactory.fillDefaults().grab(true, true).applyTo(bookmarkCommentViewer); addBulbDecorator(bookmarkCommentViewer.getTextWidget(), "Content assist available"); bookmarkCommentViewer.setBookmark(null); } private void updateFormToolbar(final Bookmark bookmark) { IContributionItem[] items = form.getToolBarManager().getItems(); for (IContributionItem item : items) { IContributionItem removed = form.getToolBarManager().remove(item); if (removed != null) { item.dispose(); } } if (bookmark == null) { form.getToolBarManager().update(false); return; } Optional<IImportTeamProject> importTeamProject = BookmarksPlugin.getDefault().getImportTeamProjectProvider() .getHandler(bookmark); if (importTeamProject.isPresent()) { Action importProjectAction = new Action("Import project", IAction.AS_PUSH_BUTTON) { public void run() { ImportTeamProjectFromBookmarkJob job = new ImportTeamProjectFromBookmarkJob(bookmark); job.schedule(); } }; importProjectAction.setImageDescriptor(importTeamProject.get().getIcon()); form.getToolBarManager().add(importProjectAction); } Optional<BookmarkProblem> needsUpdateBookmarkProblem = bookmarkProblems.getBookmarkProblem(bookmark.getId(), BookmarkProblem.TYPE_PROPERTIES_NEED_UPDATE); if (needsUpdateBookmarkProblem.isPresent()) { IBookmarkProblemHandler handler = bookmarkProblemHandlers .getBookmarkProblemHandler(needsUpdateBookmarkProblem.get().getProblemType()); if (handler != null) { Action updateBookmarkPropertiesAction = new Action( handler.getActionMessage(needsUpdateBookmarkProblem.get()), IAction.AS_PUSH_BUTTON) { public void run() { try { handler.handleAction(needsUpdateBookmarkProblem.get()); } catch (BookmarksException e) { ErrorDialog.openError(null, "Error", "Could not solve bookmark problem", e.getStatus()); } } }; updateBookmarkPropertiesAction .setImageDescriptor(BookmarksPlugin.getImageDescriptor(IMG_UPDATE_BOOKMARK)); updateBookmarkPropertiesAction.setEnabled(canBeModified(bookmark)); form.getToolBarManager().add(updateBookmarkPropertiesAction); } } form.getToolBarManager().update(true); } private boolean canBeModified(final Bookmark bookmark) { IStatus status = bookmarkDatabase.getBookmarksModificationValidator() .validateModification(bookmarkDatabase.getBookmarksTree(), bookmark.getId()); return status.isOK(); } private void addBulbDecorator(final Control control, final String tooltip) { ControlDecoration dec = new ControlDecoration(control, SWT.TOP | SWT.LEFT); dec.setImage(FieldDecorationRegistry.getDefault() .getFieldDecoration(FieldDecorationRegistry.DEC_CONTENT_PROPOSAL).getImage()); dec.setShowOnlyOnFocus(true); dec.setShowHover(true); dec.setDescriptionText(tooltip); } @Override public void dispose() { getSite().getPage().removePartListener(previousActivePartListener); bookmarkDatabase.removeListener(bookmarksListener); eventBroker.unsubscribe(bookmarkProblemsEventHandler); toggleLinkAction.dispose(); toolkit.dispose(); if (icon != null) { icon.dispose(); } super.dispose(); } private void createTreeControl(Composite parent) { IBookmarkPropertiesProvider bookmarkPropertiesProvider = BookmarksPlugin.getDefault() .getBookmarkPropertiesProvider(); BookmarkId rootId = bookmarkDatabase.getBookmarksTree().getRootFolder().getId(); MostVisitedBookmarksVirtualFolder mostVisitedBookmarksVirtualFolder = new MostVisitedBookmarksVirtualFolder( eventBroker, bookmarkDatabase, BookmarksPlugin.getDefault().getMostVisitedBookmarks(), rootId, 10); LatestVisitedBookmarksVirtualFolder latestVisitedBookmarksVirtualFolder = new LatestVisitedBookmarksVirtualFolder( eventBroker, bookmarkDatabase, BookmarksPlugin.getDefault().getMostVisitedBookmarks(), rootId, 10); RecentBookmarksVirtualFolder recentBookmarksVirtualFolder = new RecentBookmarksVirtualFolder(eventBroker, bookmarkDatabase, BookmarksPlugin.getDefault().getRecentBookmarks(), rootId, 20); NumberedBookmarksVirtualFolder numberedBookmarksVirtualFolder = new NumberedBookmarksVirtualFolder(eventBroker, bookmarkDatabase, rootId, BookmarksPlugin.getDefault().getNumberedBookmarks()); IBookmarksDirtyStateTracker bookmarksDirtyStateTracker = BookmarksPlugin.getDefault() .getBookmarksDirtyStateTracker(); PatternFilter patternFilter = new BookmarkPatternFilter(); patternFilter.setIncludeLeadingWildcard(true); FilteredTree filteredTree = new FilteredTree(parent, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL, patternFilter, true) { protected TreeViewer doCreateTreeViewer(Composite parent, int style) { return new BookmarksTreeViewer(parent, bookmarkDatabase, bookmarksDirtyStateTracker, remoteBookmarksStoreManager, bookmarkPropertiesProvider, Lists.newArrayList(mostVisitedBookmarksVirtualFolder, latestVisitedBookmarksVirtualFolder, recentBookmarksVirtualFolder, numberedBookmarksVirtualFolder)); }; }; filteredTree.setQuickSelectionMode(true); bookmarksTreeViewer = (BookmarksTreeViewer) filteredTree.getViewer(); drillDownAdapter = new DrillDownAdapter(bookmarksTreeViewer); bookmarksTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { final Bookmark bookmark = bookmarksTreeViewer.getSelectedBookmark(); updateFormToolbar(bookmark); bookmarkCommentViewer.setBookmark(bookmark); updateFormBookmarkProblems(bookmark); } }); hookDoubleClickAction(); } private void hookContextMenu() { MenuManager menuMgr = new MenuManager("#PopupMenu"); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { BookmarksView.this.fillContextMenu(manager); } }); Menu menu = menuMgr.createContextMenu(bookmarksTreeViewer.getControl()); bookmarksTreeViewer.getControl().setMenu(menu); getSite().registerContextMenu(menuMgr, bookmarksTreeViewer); } private void contributeToActionBars() { IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); fillLocalToolBar(bars.getToolBarManager()); } private void fillLocalPullDown(IMenuManager manager) { manager.add(refreshAction); manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } private void fillContextMenu(IMenuManager manager) { addRemoteBookmarksStoreActions(manager); // Other plug-ins can contribute there actions here manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); manager.add(new Separator()); drillDownAdapter.addNavigationActions(manager); } private void addRemoteBookmarksStoreActions(IMenuManager manager) { for (IRemoteBookmarksStore store : BookmarksPlugin.getDefault().getRemoteBookmarksStoreManager() .getRemoteBookmarksStores()) { MenuManager subMenu = new MenuManager(store.getDescriptor().getLabel(), ID + "." + store.getDescriptor().getId()); AddToRemoteBookmarksStoreAction addToStoreAction = new AddToRemoteBookmarksStoreAction(eventBroker, bookmarksTreeViewer, store); RemoveFromRemoteBookmarksStoreAction removeFromStoreAction = new RemoveFromRemoteBookmarksStoreAction( eventBroker, bookmarksTreeViewer, store); subMenu.add(addToStoreAction); subMenu.add(removeFromStoreAction); // Other plug-ins can contribute there actions here subMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); manager.add(subMenu); } } private void fillLocalToolBar(IToolBarManager manager) { manager.add(collapseAllAction); manager.add(refreshAction); manager.add(toggleLinkAction); manager.add(new Separator()); drillDownAdapter.addNavigationActions(manager); addConnectToRemoteBookmarksStoreActions(manager); } private void addConnectToRemoteBookmarksStoreActions(IContributionManager manager) { for (IRemoteBookmarksStore store : BookmarksPlugin.getDefault().getRemoteBookmarksStoreManager() .getRemoteBookmarksStores()) { ConnectToRemoteBookmarksStoreAction connectAction = new ConnectToRemoteBookmarksStoreAction(eventBroker, store); manager.add(connectAction); } } private void makeActions() { collapseAllAction = new CollapseAllAction(bookmarksTreeViewer); refreshAction = new RefreshRemoteFoldersAction(bookmarkDatabase, remoteBookmarksStoreManager, bookmarksDirtyStateTracker); toggleLinkAction = new ToggleLinkAction(bookmarkDatabase, getSite(), bookmarksTreeViewer); } public void setFocus() { bookmarksTreeViewer.getControl().setFocus(); } @Override public void init(IViewSite site, IMemento memento) throws PartInitException { this.memento = memento; super.init(site, memento); getSite().getPage().addPartListener(previousActivePartListener); } @Override public void saveState(IMemento memento) { BookmarksTreeViewerStateManager manager = new BookmarksTreeViewerStateManager(bookmarksTreeViewer); manager.saveState(memento); } private void restoreState(IMemento memento) { BookmarksTreeViewerStateManager manager = new BookmarksTreeViewerStateManager(bookmarksTreeViewer); manager.restoreState(memento); } private void hookDoubleClickAction() { bookmarksTreeViewer.addDoubleClickListener(event -> { ISelection selection = bookmarksTreeViewer.getSelection(); Object firstElement = ((IStructuredSelection) selection).getFirstElement(); Bookmark bookmark = AdapterUtils.getAdapter(firstElement, Bookmark.class); if (bookmark instanceof BookmarkFolder) { bookmarksTreeViewer.setExpandedState(firstElement, !bookmarksTreeViewer.getExpandedState(firstElement)); } else { IHandlerService handlerService = (IHandlerService) getSite().getService(IHandlerService.class); try { handlerService.executeCommand(COMMAND_ID_GOTO_FAVORI, null); } catch (ExecutionException | NotDefinedException | NotEnabledException | NotHandledException e) { StatusHelper.logError("Could not go to bookmark", e); } } }); } private void updateFormBookmarkProblems(Bookmark bookmark) { if (bookmark == null) { form.setMessage(null); return; } Set<BookmarkProblem> problems = bookmarkProblems.getBookmarkProblems(bookmark.getId()); if (problems.size() == 0) { form.setMessage(null); return; } int type = problems.iterator().next().getSeverity() == Severity.ERROR ? IMessageProvider.ERROR : IMessageProvider.WARNING; form.setMessage(problems.size() == 1 ? "One bookmark problem detected" : "" + problems.size() + " bookmark problems detected", type); if (bookmarkProblemsTooltip == null) { Control control = Stream.of(form.getHead().getChildren()).filter(child -> child instanceof CLabel) .findFirst().get(); bookmarkProblemsTooltip = new BookmarkProblemsTooltip(toolkit, control, ToolTip.NO_RECREATE, bookmarkProblems, bookmarkProblemHandlers) { public Point getLocation(Point tipSize, Event event) { Rectangle bounds = control.getBounds(); return control.getParent().toDisplay(bounds.x, bounds.y); } }; bookmarkProblemsTooltip.setHideOnMouseDown(false); } bookmarkProblemsTooltip.setBookmark(bookmark.getId()); } public IWorkbenchPart getPreviousActivePart() { return previousActivePartListener.getPreviousActivePart(); } private void refreshPropertyPage() { Display.getDefault().asyncExec(() -> { if (propertyPage != null) { propertyPage.refresh(); } }); } @Override public Object getAdapter(Class adapter) { if (adapter == IPropertySheetPage.class) { if (propertyPage == null) { propertyPage = new PropertySheetPage(); } return propertyPage; } if (adapter == IShowInSource.class) { return new IShowInSource() { public ShowInContext getShowInContext() { return new ShowInContext(null, bookmarksTreeViewer.getSelection()); } }; } return super.getAdapter(adapter); } }
bundles/mesfavoris/src/mesfavoris/internal/views/BookmarksView.java
package mesfavoris.internal.views; import static mesfavoris.internal.IUIConstants.IMG_UPDATE_BOOKMARK; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.NotEnabledException; import org.eclipse.core.commands.NotHandledException; import org.eclipse.core.commands.common.NotDefinedException; import org.eclipse.core.runtime.IStatus; import org.eclipse.e4.core.services.events.IEventBroker; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.action.IContributionManager; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.fieldassist.FieldDecorationRegistry; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; 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.TreeViewer; import org.eclipse.jface.window.ToolTip; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IMemento; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.FilteredTree; import org.eclipse.ui.dialogs.PatternFilter; import org.eclipse.ui.forms.HyperlinkSettings; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.Form; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.part.DrillDownAdapter; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.views.properties.IPropertySheetPage; import org.eclipse.ui.views.properties.PropertySheetPage; import org.osgi.service.event.EventHandler; import com.google.common.collect.Lists; import mesfavoris.BookmarksException; import mesfavoris.bookmarktype.IBookmarkPropertiesProvider; import mesfavoris.bookmarktype.IImportTeamProject; import mesfavoris.commons.core.AdapterUtils; import mesfavoris.internal.BookmarksPlugin; import mesfavoris.internal.IUIConstants; import mesfavoris.internal.StatusHelper; import mesfavoris.internal.actions.AddToRemoteBookmarksStoreAction; import mesfavoris.internal.actions.CollapseAllAction; import mesfavoris.internal.actions.ConnectToRemoteBookmarksStoreAction; import mesfavoris.internal.actions.RefreshRemoteFoldersAction; import mesfavoris.internal.actions.RemoveFromRemoteBookmarksStoreAction; import mesfavoris.internal.actions.ToggleLinkAction; import mesfavoris.internal.jobs.ImportTeamProjectFromBookmarkJob; import mesfavoris.internal.numberedbookmarks.NumberedBookmarksVirtualFolder; import mesfavoris.internal.problems.extension.BookmarkProblemHandlers; import mesfavoris.internal.problems.ui.BookmarkProblemsTooltip; import mesfavoris.internal.recent.RecentBookmarksVirtualFolder; import mesfavoris.internal.views.comment.BookmarkCommentArea; import mesfavoris.internal.visited.LatestVisitedBookmarksVirtualFolder; import mesfavoris.internal.visited.MostVisitedBookmarksVirtualFolder; import mesfavoris.model.Bookmark; import mesfavoris.model.BookmarkDatabase; import mesfavoris.model.BookmarkFolder; import mesfavoris.model.BookmarkId; import mesfavoris.model.IBookmarksListener; import mesfavoris.persistence.IBookmarksDirtyStateTracker; import mesfavoris.problems.BookmarkProblem; import mesfavoris.problems.BookmarkProblem.Severity; import mesfavoris.problems.IBookmarkProblemHandler; import mesfavoris.problems.IBookmarkProblems; import mesfavoris.remote.IRemoteBookmarksStore; import mesfavoris.remote.RemoteBookmarksStoreManager; import mesfavoris.topics.BookmarksEvents; public class BookmarksView extends ViewPart { private static final String COMMAND_ID_GOTO_FAVORI = "mesfavoris.command.gotoFavori"; public static final String ID = "mesfavoris.views.BookmarksView"; private final BookmarkDatabase bookmarkDatabase; private final IEventBroker eventBroker; private final RemoteBookmarksStoreManager remoteBookmarksStoreManager; private final IBookmarksDirtyStateTracker bookmarksDirtyStateTracker; private final IBookmarkProblems bookmarkProblems; private final BookmarkProblemHandlers bookmarkProblemHandlers; private final EventHandler bookmarkProblemsEventHandler; private BookmarksTreeViewer bookmarksTreeViewer; private BookmarkCommentArea bookmarkCommentViewer; private DrillDownAdapter drillDownAdapter; private Action refreshAction; private Action collapseAllAction; private ToggleLinkAction toggleLinkAction; private FormToolkit toolkit; private Form form; private IMemento memento; private PreviousActivePartListener previousActivePartListener = new PreviousActivePartListener(); private Composite commentsComposite; private Section commentsSection; private BookmarkProblemsTooltip bookmarkProblemsTooltip; private Image icon; private PropertySheetPage propertyPage; private final IBookmarksListener bookmarksListener = (modifications) -> refreshPropertyPage(); public BookmarksView() { this.bookmarkDatabase = BookmarksPlugin.getDefault().getBookmarkDatabase(); this.eventBroker = (IEventBroker) PlatformUI.getWorkbench().getService(IEventBroker.class); this.remoteBookmarksStoreManager = BookmarksPlugin.getDefault().getRemoteBookmarksStoreManager(); this.bookmarksDirtyStateTracker = BookmarksPlugin.getDefault().getBookmarksDirtyStateTracker(); this.bookmarkProblems = BookmarksPlugin.getDefault().getBookmarkProblems(); this.bookmarkProblemHandlers = BookmarksPlugin.getDefault().getBookmarkProblemHandlers(); bookmarkProblemsEventHandler = (event) -> { refreshPropertyPage(); updateFormBookmarkProblems(bookmarksTreeViewer.getSelectedBookmark()); updateFormToolbar(bookmarksTreeViewer.getSelectedBookmark()); }; } public void createPartControl(Composite parent) { GridLayoutFactory.fillDefaults().applyTo(parent); toolkit = new FormToolkit(parent.getDisplay()); toolkit.getHyperlinkGroup().setHyperlinkUnderlineMode(HyperlinkSettings.UNDERLINE_HOVER); form = toolkit.createForm(parent); icon = BookmarksPlugin.getImageDescriptor(IUIConstants.IMG_BOOKMARKS).createImage(); form.setImage(icon); GridDataFactory.fillDefaults().grab(true, true).applyTo(form); form.setText("Mes Favoris"); toolkit.decorateFormHeading(form); GridLayoutFactory.swtDefaults().applyTo(form.getBody()); SashForm sashForm = new SashForm(form.getBody(), SWT.VERTICAL); toolkit.adapt(sashForm, true, true); GridDataFactory.fillDefaults().grab(true, true).applyTo(sashForm); createTreeControl(sashForm); createCommentsSection(sashForm); makeActions(); hookContextMenu(); contributeToActionBars(); getSite().setSelectionProvider(bookmarksTreeViewer); toggleLinkAction.init(); restoreState(memento); bookmarkDatabase.addListener(bookmarksListener); eventBroker.subscribe(BookmarksEvents.TOPIC_BOOKMARK_PROBLEMS_CHANGED, bookmarkProblemsEventHandler); } private void createCommentsSection(Composite parent) { commentsSection = toolkit.createSection(parent, ExpandableComposite.TITLE_BAR); commentsSection.setText("Comments"); commentsSection.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).create()); commentsComposite = toolkit.createComposite(commentsSection); toolkit.paintBordersFor(commentsComposite); commentsSection.setClient(commentsComposite); GridLayoutFactory.fillDefaults().extendedMargins(2, 2, 2, 2).applyTo(commentsComposite); bookmarkCommentViewer = new BookmarkCommentArea(commentsComposite, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP | toolkit.getBorderStyle(), bookmarkDatabase); bookmarkCommentViewer.getTextWidget().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); GridDataFactory.fillDefaults().grab(true, true).applyTo(bookmarkCommentViewer); addBulbDecorator(bookmarkCommentViewer.getTextWidget(), "Content assist available"); bookmarkCommentViewer.setBookmark(null); } private void updateFormToolbar(final Bookmark bookmark) { IContributionItem[] items = form.getToolBarManager().getItems(); for (IContributionItem item : items) { IContributionItem removed = form.getToolBarManager().remove(item); if (removed != null) { item.dispose(); } } if (bookmark == null) { form.getToolBarManager().update(false); return; } Optional<IImportTeamProject> importTeamProject = BookmarksPlugin.getDefault().getImportTeamProjectProvider() .getHandler(bookmark); if (importTeamProject.isPresent()) { Action importProjectAction = new Action("Import project", IAction.AS_PUSH_BUTTON) { public void run() { ImportTeamProjectFromBookmarkJob job = new ImportTeamProjectFromBookmarkJob(bookmark); job.schedule(); } }; importProjectAction.setImageDescriptor(importTeamProject.get().getIcon()); form.getToolBarManager().add(importProjectAction); } Optional<BookmarkProblem> needsUpdateBookmarkProblem = bookmarkProblems.getBookmarkProblem(bookmark.getId(), BookmarkProblem.TYPE_PROPERTIES_NEED_UPDATE); if (needsUpdateBookmarkProblem.isPresent()) { IBookmarkProblemHandler handler = bookmarkProblemHandlers .getBookmarkProblemHandler(needsUpdateBookmarkProblem.get().getProblemType()); if (handler != null) { Action updateBookmarkPropertiesAction = new Action( handler.getActionMessage(needsUpdateBookmarkProblem.get()), IAction.AS_PUSH_BUTTON) { public void run() { try { handler.handleAction(needsUpdateBookmarkProblem.get()); } catch (BookmarksException e) { ErrorDialog.openError(null, "Error", "Could not solve bookmark problem", e.getStatus()); } } }; updateBookmarkPropertiesAction .setImageDescriptor(BookmarksPlugin.getImageDescriptor(IMG_UPDATE_BOOKMARK)); updateBookmarkPropertiesAction.setEnabled(canBeModified(bookmark)); form.getToolBarManager().add(updateBookmarkPropertiesAction); } } form.getToolBarManager().update(true); } private boolean canBeModified(final Bookmark bookmark) { IStatus status = bookmarkDatabase.getBookmarksModificationValidator() .validateModification(bookmarkDatabase.getBookmarksTree(), bookmark.getId()); return status.isOK(); } private void addBulbDecorator(final Control control, final String tooltip) { ControlDecoration dec = new ControlDecoration(control, SWT.TOP | SWT.LEFT); dec.setImage(FieldDecorationRegistry.getDefault() .getFieldDecoration(FieldDecorationRegistry.DEC_CONTENT_PROPOSAL).getImage()); dec.setShowOnlyOnFocus(true); dec.setShowHover(true); dec.setDescriptionText(tooltip); } @Override public void dispose() { getSite().getPage().removePartListener(previousActivePartListener); bookmarkDatabase.removeListener(bookmarksListener); eventBroker.unsubscribe(bookmarkProblemsEventHandler); toggleLinkAction.dispose(); toolkit.dispose(); if (icon != null) { icon.dispose(); } super.dispose(); } private void createTreeControl(Composite parent) { IBookmarkPropertiesProvider bookmarkPropertiesProvider = BookmarksPlugin.getDefault() .getBookmarkPropertiesProvider(); BookmarkId rootId = bookmarkDatabase.getBookmarksTree().getRootFolder().getId(); MostVisitedBookmarksVirtualFolder mostVisitedBookmarksVirtualFolder = new MostVisitedBookmarksVirtualFolder( eventBroker, bookmarkDatabase, BookmarksPlugin.getDefault().getMostVisitedBookmarks(), rootId, 10); LatestVisitedBookmarksVirtualFolder latestVisitedBookmarksVirtualFolder = new LatestVisitedBookmarksVirtualFolder( eventBroker, bookmarkDatabase, BookmarksPlugin.getDefault().getMostVisitedBookmarks(), rootId, 10); RecentBookmarksVirtualFolder recentBookmarksVirtualFolder = new RecentBookmarksVirtualFolder(eventBroker, bookmarkDatabase, BookmarksPlugin.getDefault().getRecentBookmarks(), rootId, 20); NumberedBookmarksVirtualFolder numberedBookmarksVirtualFolder = new NumberedBookmarksVirtualFolder(eventBroker, bookmarkDatabase, rootId, BookmarksPlugin.getDefault().getNumberedBookmarks()); IBookmarksDirtyStateTracker bookmarksDirtyStateTracker = BookmarksPlugin.getDefault() .getBookmarksDirtyStateTracker(); PatternFilter patternFilter = new BookmarkPatternFilter(); patternFilter.setIncludeLeadingWildcard(true); FilteredTree filteredTree = new FilteredTree(parent, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL, patternFilter, true) { protected TreeViewer doCreateTreeViewer(Composite parent, int style) { return new BookmarksTreeViewer(parent, bookmarkDatabase, bookmarksDirtyStateTracker, remoteBookmarksStoreManager, bookmarkPropertiesProvider, Lists.newArrayList(mostVisitedBookmarksVirtualFolder, latestVisitedBookmarksVirtualFolder, recentBookmarksVirtualFolder, numberedBookmarksVirtualFolder)); }; }; filteredTree.setQuickSelectionMode(true); bookmarksTreeViewer = (BookmarksTreeViewer) filteredTree.getViewer(); drillDownAdapter = new DrillDownAdapter(bookmarksTreeViewer); bookmarksTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { final Bookmark bookmark = bookmarksTreeViewer.getSelectedBookmark(); updateFormToolbar(bookmark); bookmarkCommentViewer.setBookmark(bookmark); updateFormBookmarkProblems(bookmark); } }); hookDoubleClickAction(); } private void hookContextMenu() { MenuManager menuMgr = new MenuManager("#PopupMenu"); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { BookmarksView.this.fillContextMenu(manager); } }); Menu menu = menuMgr.createContextMenu(bookmarksTreeViewer.getControl()); bookmarksTreeViewer.getControl().setMenu(menu); getSite().registerContextMenu(menuMgr, bookmarksTreeViewer); } private void contributeToActionBars() { IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); fillLocalToolBar(bars.getToolBarManager()); } private void fillLocalPullDown(IMenuManager manager) { manager.add(refreshAction); manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } private void fillContextMenu(IMenuManager manager) { addRemoteBookmarksStoreActions(manager); // Other plug-ins can contribute there actions here manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); manager.add(new Separator()); drillDownAdapter.addNavigationActions(manager); } private void addRemoteBookmarksStoreActions(IMenuManager manager) { for (IRemoteBookmarksStore store : BookmarksPlugin.getDefault().getRemoteBookmarksStoreManager() .getRemoteBookmarksStores()) { MenuManager subMenu = new MenuManager(store.getDescriptor().getLabel(), ID + "." + store.getDescriptor().getId()); AddToRemoteBookmarksStoreAction addToStoreAction = new AddToRemoteBookmarksStoreAction(eventBroker, bookmarksTreeViewer, store); RemoveFromRemoteBookmarksStoreAction removeFromStoreAction = new RemoveFromRemoteBookmarksStoreAction( eventBroker, bookmarksTreeViewer, store); subMenu.add(addToStoreAction); subMenu.add(removeFromStoreAction); // Other plug-ins can contribute there actions here subMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); manager.add(subMenu); } } private void fillLocalToolBar(IToolBarManager manager) { manager.add(collapseAllAction); manager.add(refreshAction); manager.add(toggleLinkAction); manager.add(new Separator()); drillDownAdapter.addNavigationActions(manager); addConnectToRemoteBookmarksStoreActions(manager); } private void addConnectToRemoteBookmarksStoreActions(IContributionManager manager) { for (IRemoteBookmarksStore store : BookmarksPlugin.getDefault().getRemoteBookmarksStoreManager() .getRemoteBookmarksStores()) { ConnectToRemoteBookmarksStoreAction connectAction = new ConnectToRemoteBookmarksStoreAction(eventBroker, store); manager.add(connectAction); } } private void makeActions() { collapseAllAction = new CollapseAllAction(bookmarksTreeViewer); refreshAction = new RefreshRemoteFoldersAction(bookmarkDatabase, remoteBookmarksStoreManager, bookmarksDirtyStateTracker); toggleLinkAction = new ToggleLinkAction(bookmarkDatabase, getSite(), bookmarksTreeViewer); } public void setFocus() { bookmarksTreeViewer.getControl().setFocus(); } @Override public void init(IViewSite site, IMemento memento) throws PartInitException { this.memento = memento; super.init(site, memento); getSite().getPage().addPartListener(previousActivePartListener); } @Override public void saveState(IMemento memento) { BookmarksTreeViewerStateManager manager = new BookmarksTreeViewerStateManager(bookmarksTreeViewer); manager.saveState(memento); } private void restoreState(IMemento memento) { BookmarksTreeViewerStateManager manager = new BookmarksTreeViewerStateManager(bookmarksTreeViewer); manager.restoreState(memento); } private void hookDoubleClickAction() { bookmarksTreeViewer.addDoubleClickListener(event -> { ISelection selection = bookmarksTreeViewer.getSelection(); Object firstElement = ((IStructuredSelection) selection).getFirstElement(); Bookmark bookmark = AdapterUtils.getAdapter(firstElement, Bookmark.class); if (bookmark instanceof BookmarkFolder) { bookmarksTreeViewer.setExpandedState(firstElement, !bookmarksTreeViewer.getExpandedState(firstElement)); } else { IHandlerService handlerService = (IHandlerService) getSite().getService(IHandlerService.class); try { handlerService.executeCommand(COMMAND_ID_GOTO_FAVORI, null); } catch (ExecutionException | NotDefinedException | NotEnabledException | NotHandledException e) { StatusHelper.logError("Could not go to bookmark", e); } } }); } private void updateFormBookmarkProblems(Bookmark bookmark) { if (bookmark == null) { form.setMessage(null); return; } Set<BookmarkProblem> problems = bookmarkProblems.getBookmarkProblems(bookmark.getId()); if (problems.size() == 0) { form.setMessage(null); return; } int type = problems.iterator().next().getSeverity() == Severity.ERROR ? IMessageProvider.ERROR : IMessageProvider.WARNING; form.setMessage(problems.size() == 1 ? "One bookmark problem detected" : "" + problems.size() + " bookmark problems detected", type); if (bookmarkProblemsTooltip == null) { Control control = Stream.of(form.getHead().getChildren()).filter(child -> child instanceof CLabel) .findFirst().get(); bookmarkProblemsTooltip = new BookmarkProblemsTooltip(toolkit, control, ToolTip.NO_RECREATE, bookmarkProblems, bookmarkProblemHandlers) { public Point getLocation(Point tipSize, Event event) { Rectangle bounds = control.getBounds(); return control.getParent().toDisplay(bounds.x, bounds.y); } }; bookmarkProblemsTooltip.setHideOnMouseDown(false); } bookmarkProblemsTooltip.setBookmark(bookmark.getId()); } public IWorkbenchPart getPreviousActivePart() { return previousActivePartListener.getPreviousActivePart(); } private void refreshPropertyPage() { Display.getDefault().asyncExec(() -> { if (propertyPage != null) { propertyPage.refresh(); } }); } @Override public Object getAdapter(Class adapter) { if (adapter == IPropertySheetPage.class) { if (propertyPage == null) { propertyPage = new PropertySheetPage(); } return propertyPage; } return super.getAdapter(adapter); } }
BookmarksView can now adapt to IShowInSource
bundles/mesfavoris/src/mesfavoris/internal/views/BookmarksView.java
BookmarksView can now adapt to IShowInSource
<ide><path>undles/mesfavoris/src/mesfavoris/internal/views/BookmarksView.java <ide> import org.eclipse.ui.forms.widgets.Section; <ide> import org.eclipse.ui.handlers.IHandlerService; <ide> import org.eclipse.ui.part.DrillDownAdapter; <add>import org.eclipse.ui.part.IShowInSource; <add>import org.eclipse.ui.part.ShowInContext; <ide> import org.eclipse.ui.part.ViewPart; <ide> import org.eclipse.ui.views.properties.IPropertySheetPage; <ide> import org.eclipse.ui.views.properties.PropertySheetPage; <ide> } <ide> return propertyPage; <ide> } <add> if (adapter == IShowInSource.class) { <add> return new IShowInSource() { <add> public ShowInContext getShowInContext() { <add> return new ShowInContext(null, bookmarksTreeViewer.getSelection()); <add> } <add> }; <add> } <ide> return super.getAdapter(adapter); <ide> } <ide>
Java
mit
4a0946306ac27f8ff7ac97574aa804f6724749be
0
elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin
package com.elmakers.mine.bukkit.plugins.magic; import java.io.File; import java.io.InputStream; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.TreeSpecies; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerExpChangeEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; import com.elmakers.mine.bukkit.utilities.InventoryUtils; import com.elmakers.mine.bukkit.utilities.Messages; import com.elmakers.mine.bukkit.utilities.borrowed.Configuration; import com.elmakers.mine.bukkit.utilities.borrowed.ConfigurationNode; public class Wand implements CostReducer { protected final static int inventorySize = 27; protected final static int inventoryOrganizeSize = 16; protected final static int inventoryOrganizeNewGroupSize = 8; protected final static int hotbarSize = 9; private ItemStack item; private Spells spells; private PlayerSpells activePlayer; // Cached state private String id; private Inventory hotbar; private List<Inventory> inventories; private String activeSpell = ""; private String activeMaterial = ""; private String wandName = ""; private String description = ""; private String owner = ""; private float costReduction = 0; private float cooldownReduction = 0; private float damageReduction = 0; private float damageReductionPhysical = 0; private float damageReductionProjectiles = 0; private float damageReductionFalling = 0; private float damageReductionFire = 0; private float damageReductionExplosions = 0; private float power = 0; private boolean hasInventory = false; private boolean modifiable = true; private int uses = 0; private int xp = 0; private int xpRegeneration = 0; private int xpMax = 50; private int healthRegeneration = 0; private int hungerRegeneration = 0; private int effectColor = 0; private float defaultWalkSpeed = 0.2f; private float defaultFlySpeed = 0.1f; private float speedIncrease = 0; private int storedXpLevel = 0; private int storedXp = 0; private float storedXpProgress = 0; private static DecimalFormat floatFormat = new DecimalFormat("#.###"); public static Material WandMaterial = Material.BLAZE_ROD; public static Material EnchantableWandMaterial = Material.WOOD_SWORD; public static Material EraseMaterial = Material.SULPHUR; public static Material CopyMaterial = Material.PUMPKIN_SEEDS; // Wand configurations protected static Map<String, ConfigurationNode> wandTemplates = new HashMap<String, ConfigurationNode>(); private static final String propertiesFileName = "wands.yml"; private static final String propertiesFileNameDefaults = "wands.defaults.yml"; // Inventory functionality int openInventoryPage = 0; boolean inventoryIsOpen = false; private Wand() { hotbar = InventoryUtils.createInventory(null, 9, "Wand"); inventories = new ArrayList<Inventory>(); } public Wand(Spells spells) { this(); this.spells = spells; item = new ItemStack(WandMaterial); // This will make the Bukkit ItemStack into a real ItemStack with NBT data. item = InventoryUtils.getCopy(item); ItemMeta itemMeta = item.getItemMeta(); item.setItemMeta(itemMeta); InventoryUtils.addGlow(item); id = UUID.randomUUID().toString(); wandName = Messages.get("wand.default_name"); updateName(); saveState(); } public Wand(Spells spells, ItemStack item) { this(); this.item = item; this.spells = spells; loadState(); } public void setActiveSpell(String activeSpell) { this.activeSpell = activeSpell; updateName(); updateInventoryNames(true); saveState(); } @SuppressWarnings("deprecation") public void setActiveMaterial(Material material, byte data) { String materialKey = ""; if (material == CopyMaterial) { materialKey = "-1:0"; } else if (material == EraseMaterial) { materialKey = "0:0"; } else { materialKey = material.getId() + ":" + data; } setActiveMaterial(materialKey); } protected void setActiveMaterial(String materialKey) { this.activeMaterial = materialKey; updateName(); updateActiveMaterial(); updateInventoryNames(true); saveState(); } public int getXpRegeneration() { return xpRegeneration; } public int getXpMax() { return xpMax; } public int getExperience() { return xp; } public void removeExperience(int amount) { xp = Math.max(0, xp - amount); updateMana(); } public int getHealthRegeneration() { return healthRegeneration; } public int getHungerRegeneration() { return hungerRegeneration; } public float getCostReduction() { return costReduction; } public boolean isModifiable() { return modifiable; } public boolean usesMana() { return xpMax > 0 && xpRegeneration > 0; } public float getCooldownReduction() { return cooldownReduction; } public boolean getHasInventory() { return hasInventory; } public float getPower() { return power; } public float getDamageReduction() { return damageReduction; } public float getDamageReductionPhysical() { return damageReductionPhysical; } public float getDamageReductionProjectiles() { return damageReductionProjectiles; } public float getDamageReductionFalling() { return damageReductionFalling; } public float getDamageReductionFire() { return damageReductionFire; } public float getDamageReductionExplosions() { return damageReductionExplosions; } public int getUses() { return uses; } public String getName() { return wandName; } public String getDescription() { return description; } public String getOwner() { return owner; } protected void setName(String name) { wandName = name; updateName(); } protected void setDescription(String description) { this.description = description; updateLore(); } protected void takeOwnership(Player player) { owner = player.getName(); } public void takeOwnership(Player player, String name, boolean updateDescription) { setName(name); takeOwnership(player); if (updateDescription) { setDescription(Messages.get("wand.owner_description", "$name's Wand").replace("$name", owner)); } } public ItemStack getItem() { return item; } public void setItem(ItemStack item) { this.item = item; } protected List<Inventory> getAllInventories() { List<Inventory> allInventories = new ArrayList<Inventory>(inventories.size() + 1); allInventories.add(hotbar); allInventories.addAll(inventories); return allInventories; } protected Set<String> getSpells() { return getSpells(false); } protected Set<String> getSpells(boolean includePositions) { Set<String> spellNames = new TreeSet<String>(); List<Inventory> allInventories = getAllInventories(); int index = 0; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int i = 0; i < items.length; i++) { if (items[i] != null && !isWand(items[i])) { if (isSpell(items[i])) { String spellName = getSpell(items[i]); if (includePositions) { spellName += "@" + index; } spellNames.add(spellName); } } index++; } } return spellNames; } protected String getSpellString() { return StringUtils.join(getSpells(true), "|"); } protected Set<String> getMaterialNames() { return getMaterialNames(false); } protected static String getMaterialKey(ItemStack itemStack) { return getMaterialKey(itemStack, null); } @SuppressWarnings("deprecation") protected static String getMaterialKey(ItemStack itemStack, Integer index) { if (itemStack == null || isSpell(itemStack) || isWand(itemStack)) { return null; } Material material = itemStack.getType(); if (material == Material.AIR) { return null; } String materialKey = material.getId() + ":" + itemStack.getData().getData(); if (material == EraseMaterial) { materialKey = "0:0"; } else if (material == CopyMaterial) { materialKey = "-1:0"; } if (index != null) { materialKey += "@" + index; } return materialKey; } protected Set<String> getMaterialNames(boolean includePositions) { Set<String> materialNames = new TreeSet<String>(); List<Inventory> allInventories = new ArrayList<Inventory>(inventories.size() + 1); allInventories.add(hotbar); allInventories.addAll(inventories); Integer index = 0; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int i = 0; i < items.length; i++) { String materialKey = getMaterialKey(items[i], includePositions ? index : null); if (materialKey != null) { materialNames.add(materialKey); } index++; } } return materialNames; } protected String getMaterialString() { return StringUtils.join(getMaterialNames(true), "|"); } protected Integer parseSlot(String[] pieces) { Integer slot = null; if (pieces.length > 0) { try { slot = Integer.parseInt(pieces[1]); } catch (Exception ex) { slot = null; } if (slot != null && slot < 0) { slot = null; } } return slot; } protected void addToInventory(ItemStack itemStack) { List<Inventory> allInventories = getAllInventories(); boolean added = false; // Set the wand item Integer selectedItem = null; if (activePlayer != null && activePlayer.getPlayer() != null) { selectedItem = activePlayer.getPlayer().getInventory().getHeldItemSlot(); hotbar.setItem(selectedItem, item); } for (Inventory inventory : allInventories) { HashMap<Integer, ItemStack> returned = inventory.addItem(itemStack); if (returned.size() == 0) { added = true; break; } } if (!added) { Inventory newInventory = InventoryUtils.createInventory(null, inventorySize, "Wand"); newInventory.addItem(itemStack); inventories.add(newInventory); } if (selectedItem != null) { hotbar.setItem(selectedItem, null); } } protected Inventory getInventoryByIndex(int inventoryIndex) { while (inventoryIndex >= inventories.size()) { inventories.add(InventoryUtils.createInventory(null, inventorySize, "Wand")); } return inventories.get(inventoryIndex); } protected Inventory getInventory(Integer slot) { Inventory inventory = hotbar; if (slot >= hotbarSize) { int inventoryIndex = (slot - hotbarSize) / inventorySize; inventory = getInventoryByIndex(inventoryIndex); } return inventory; } protected int getInventorySlot(Integer slot) { if (slot < hotbarSize) { return slot; } return ((slot - hotbarSize) % inventorySize); } protected void addToInventory(ItemStack itemStack, Integer slot) { if (slot == null) { addToInventory(itemStack); return; } Inventory inventory = getInventory(slot); slot = getInventorySlot(slot); ItemStack existing = inventory.getItem(slot); inventory.setItem(slot, itemStack); if (existing != null && existing.getType() != Material.AIR) { addToInventory(existing); } } protected void parseInventoryStrings(String spellString, String materialString) { hotbar.clear(); inventories.clear(); String[] spellNames = StringUtils.split(spellString, "|"); for (String spellName : spellNames) { String[] pieces = spellName.split("@"); Integer slot = parseSlot(pieces); ItemStack itemStack = createSpellItem(pieces[0]); if (itemStack == null) continue; addToInventory(itemStack, slot); } String[] materialNames = StringUtils.split(materialString, "|"); for (String materialName : materialNames) { String[] pieces = materialName.split("@"); Integer slot = parseSlot(pieces); ItemStack itemStack = createMaterialItem(pieces[0]); addToInventory(itemStack, slot); } hasInventory = spellNames.length + materialNames.length > 1; } @SuppressWarnings("deprecation") protected ItemStack createMaterialItem(String materialKey) { String[] nameParts = StringUtils.split(materialKey, ":"); int typeId = Integer.parseInt(nameParts[0]); if (typeId == 0) { typeId = EraseMaterial.getId(); } else if (typeId == -1) { typeId = CopyMaterial.getId(); } byte dataId = nameParts.length > 1 ? Byte.parseByte(nameParts[1]) : 0; return createMaterialItem(typeId, dataId); } protected ItemStack createSpellItem(String spellName) { Spell spell = spells.getSpell(spellName); if (spell == null) return null; if (spell.getMaterial() == null) { spells.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getName() + ", missing material"); } ItemStack itemStack = null; ItemStack originalItemStack = null; try { originalItemStack = new ItemStack(spell.getMaterial(), 1); itemStack = InventoryUtils.getCopy(originalItemStack); } catch (Exception ex) { itemStack = null; } if (itemStack == null) { spells.getPlugin().getLogger().warning("Unable to create spell icon with material " + spell.getMaterial().name()); return originalItemStack; } updateSpellName(itemStack, spell, true); return itemStack; } @SuppressWarnings("deprecation") protected ItemStack createMaterialItem(int typeId, byte dataId) { if (typeId == 0) { typeId = EraseMaterial.getId(); } else if (typeId == -1) { typeId = CopyMaterial.getId(); } ItemStack originalItemStack = new ItemStack(typeId, 1, (short)0, (byte)dataId); ItemStack itemStack = InventoryUtils.getCopy(originalItemStack); if (itemStack == null) { spells.getPlugin().getLogger().warning("Unable to create material icon for id " + typeId + ": " + originalItemStack.getType()); return originalItemStack; } ItemMeta meta = itemStack.getItemMeta(); if (typeId == EraseMaterial.getId()) { typeId = EraseMaterial.getId(); List<String> lore = new ArrayList<String>(); lore.add(Messages.get("wand.erase_material_description")); meta.setLore(lore); } else if (typeId == CopyMaterial.getId()) { typeId = EraseMaterial.getId(); List<String> lore = new ArrayList<String>(); lore.add(Messages.get("wand.copy_material_description")); meta.setLore(lore); } else { List<String> lore = new ArrayList<String>(); Material material = Material.getMaterial(typeId); if (material != null) { lore.add(ChatColor.GRAY + getMaterialName(material, (byte)dataId)); } lore.add(ChatColor.LIGHT_PURPLE + Messages.get("wand.building_material_description")); meta.setLore(lore); } meta.setDisplayName(getActiveWandName(Material.getMaterial(typeId))); itemStack.setItemMeta(meta); return itemStack; } protected void saveState() { Object wandNode = InventoryUtils.createNode(item, "wand"); InventoryUtils.setMeta(wandNode, "id", id); String wandMaterials = getMaterialString(); String wandSpells = getSpellString(); InventoryUtils.setMeta(wandNode, "materials", wandMaterials); InventoryUtils.setMeta(wandNode, "spells", wandSpells); InventoryUtils.setMeta(wandNode, "active_spell", activeSpell); InventoryUtils.setMeta(wandNode, "active_material", activeMaterial); InventoryUtils.setMeta(wandNode, "name", wandName); InventoryUtils.setMeta(wandNode, "description", description); InventoryUtils.setMeta(wandNode, "owner", owner); InventoryUtils.setMeta(wandNode, "cost_reduction", floatFormat.format(costReduction)); InventoryUtils.setMeta(wandNode, "cooldown_reduction", floatFormat.format(cooldownReduction)); InventoryUtils.setMeta(wandNode, "power", floatFormat.format(power)); InventoryUtils.setMeta(wandNode, "protection", floatFormat.format(damageReduction)); InventoryUtils.setMeta(wandNode, "protection_physical", floatFormat.format(damageReductionPhysical)); InventoryUtils.setMeta(wandNode, "protection_projectiles", floatFormat.format(damageReductionProjectiles)); InventoryUtils.setMeta(wandNode, "protection_falling", floatFormat.format(damageReductionFalling)); InventoryUtils.setMeta(wandNode, "protection_fire", floatFormat.format(damageReductionFire)); InventoryUtils.setMeta(wandNode, "protection_explosions", floatFormat.format(damageReductionExplosions)); InventoryUtils.setMeta(wandNode, "haste", floatFormat.format(speedIncrease)); InventoryUtils.setMeta(wandNode, "xp", Integer.toString(xp)); InventoryUtils.setMeta(wandNode, "xp_regeneration", Integer.toString(xpRegeneration)); InventoryUtils.setMeta(wandNode, "xp_max", Integer.toString(xpMax)); InventoryUtils.setMeta(wandNode, "health_regeneration", Integer.toString(healthRegeneration)); InventoryUtils.setMeta(wandNode, "hunger_regeneration", Integer.toString(hungerRegeneration)); InventoryUtils.setMeta(wandNode, "uses", Integer.toString(uses)); InventoryUtils.setMeta(wandNode, "has_inventory", Integer.toString((hasInventory ? 1 : 0))); InventoryUtils.setMeta(wandNode, "modifiable", Integer.toString((modifiable ? 1 : 0))); InventoryUtils.setMeta(wandNode, "effect_color", Integer.toString(effectColor, 16)); } protected void loadState() { Object wandNode = InventoryUtils.getNode(item, "wand"); if (wandNode == null) { spells.getPlugin().getLogger().warning("Found a wand with missing NBT data. This may be an old wand, or something may have wiped its data"); return; } // Don't generate a UUID unless we need to, not sure how expensive that is. id = InventoryUtils.getMeta(wandNode, "id"); id = id == null || id.length() == 0 ? UUID.randomUUID().toString() : id; wandName = InventoryUtils.getMeta(wandNode, "name", wandName); description = InventoryUtils.getMeta(wandNode, "description", description); owner = InventoryUtils.getMeta(wandNode, "owner", owner); String wandMaterials = InventoryUtils.getMeta(wandNode, "materials", ""); String wandSpells = InventoryUtils.getMeta(wandNode, "spells", ""); parseInventoryStrings(wandSpells, wandMaterials); activeSpell = InventoryUtils.getMeta(wandNode, "active_spell", activeSpell); activeMaterial = InventoryUtils.getMeta(wandNode, "active_material", activeMaterial); costReduction = Float.parseFloat(InventoryUtils.getMeta(wandNode, "cost_reduction", floatFormat.format(costReduction))); cooldownReduction = Float.parseFloat(InventoryUtils.getMeta(wandNode, "cooldown_reduction", floatFormat.format(cooldownReduction))); power = Float.parseFloat(InventoryUtils.getMeta(wandNode, "power", floatFormat.format(power))); damageReduction = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection", floatFormat.format(damageReduction))); damageReductionPhysical = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_physical", floatFormat.format(damageReductionPhysical))); damageReductionProjectiles = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_projectiles", floatFormat.format(damageReductionProjectiles))); damageReductionFalling = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_falling", floatFormat.format(damageReductionFalling))); damageReductionFire = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_fire", floatFormat.format(damageReductionFire))); damageReductionExplosions = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_explosions", floatFormat.format(damageReductionExplosions))); speedIncrease = Float.parseFloat(InventoryUtils.getMeta(wandNode, "haste", floatFormat.format(speedIncrease))); xp = Integer.parseInt(InventoryUtils.getMeta(wandNode, "xp", Integer.toString(xp))); xpRegeneration = Integer.parseInt(InventoryUtils.getMeta(wandNode, "xp_regeneration", Integer.toString(xpRegeneration))); xpMax = Integer.parseInt(InventoryUtils.getMeta(wandNode, "xp_max", Integer.toString(xpMax))); healthRegeneration = Integer.parseInt(InventoryUtils.getMeta(wandNode, "health_regeneration", Integer.toString(healthRegeneration))); hungerRegeneration = Integer.parseInt(InventoryUtils.getMeta(wandNode, "hunger_regeneration", Integer.toString(hungerRegeneration))); uses = Integer.parseInt(InventoryUtils.getMeta(wandNode, "uses", Integer.toString(uses))); hasInventory = Integer.parseInt(InventoryUtils.getMeta(wandNode, "has_inventory", (hasInventory ? "1" : "0"))) != 0; modifiable = Integer.parseInt(InventoryUtils.getMeta(wandNode, "modifiable", (modifiable ? "1" : "0"))) != 0; effectColor = Integer.parseInt(InventoryUtils.getMeta(wandNode, "effect_color", Integer.toString(effectColor, 16)), 16); // This is done here as an extra safety measure. // A walk speed too high will cause a server error. speedIncrease = Math.min(WandLevel.maxSpeedIncrease, speedIncrease); } protected void describe(CommandSender sender) { Object wandNode = InventoryUtils.getNode(item, "wand"); if (wandNode == null) { sender.sendMessage("Found a wand with missing NBT data. This may be an old wand, or something may have wiped its data"); return; } ChatColor wandColor = modifiable ? ChatColor.AQUA : ChatColor.RED; sender.sendMessage(wandColor + wandName); if (description.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + description); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + "(No Description)"); } if (owner.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + owner); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + "(No Owner)"); } String[] keys = {"active_spell", "active_material", "xp", "xp_regeneration", "xp_max", "health_regeneration", "hunger_regeneration", "uses", "cost_reduction", "cooldown_reduction", "power", "protection", "protection_physical", "protection_projectiles", "protection_falling", "protection_fire", "protection_explosions", "haste", "has_inventory", "modifiable", "effect_color", "materials", "spells"}; for (String key : keys) { String value = InventoryUtils.getMeta(wandNode, key); if (value != null && value.length() > 0) { sender.sendMessage(key + ": " + value); } } } @SuppressWarnings("deprecation") public boolean removeMaterial(Material material, byte data) { if (!modifiable) return false; if (isInventoryOpen()) { saveInventory(); } Integer id = material.getId(); String materialString = id.toString(); materialString += ":" + data; if (materialString.equals(activeMaterial)) { activeMaterial = null; } List<Inventory> allInventories = getAllInventories(); boolean found = false; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (itemStack != null && itemStack.getType() != Material.AIR && !isWand(itemStack) && !isSpell(itemStack)) { if (itemStack.getType() == material && data == itemStack.getData().getData()) { found = true; inventory.setItem(index, null); } else if (activeMaterial == null) { activeMaterial = "" + itemStack.getTypeId() + ":" + (itemStack.getData().getData()); } if (found && activeMaterial != null) { break; } } } } updateActiveMaterial(); updateInventoryNames(true); updateName(); updateLore(); saveState(); if (isInventoryOpen()) { updateInventory(); } return found; } public boolean addMaterial(Material material, byte data, boolean force) { return addMaterial(material, data, false, force); } public boolean addMaterial(Material material, byte data) { return addMaterial(material, data, false, false); } public boolean hasMaterial(int materialId, byte data) { String materialName = materialId + ":" + data; return getMaterialNames().contains(materialName); } @SuppressWarnings("deprecation") public boolean hasMaterial(Material material, byte data) { return hasMaterial(material.getId(), data); } public boolean hasSpell(String spellName) { return getSpells().contains(spellName); } public boolean addMaterial(String materialName, boolean makeActive, boolean force) { if (!modifiable && !force) return false; Integer materialId = null; byte data = 0; try { String[] pieces = materialName.split(":"); data = pieces.length > 1 ? Byte.parseByte(pieces[1]) : 0; materialId =Integer.parseInt(pieces[0]); } catch (Exception ex) { materialId = null; } if (materialId == null) { return false; } boolean addedNew = !hasMaterial(materialId, data); if (addedNew) { addToInventory(createMaterialItem(materialId, data)); } if (activeMaterial == null || activeMaterial.length() == 0 || makeActive) { activeMaterial = materialName; } updateActiveMaterial(); updateInventoryNames(true); updateName(); updateLore(); saveState(); if (isInventoryOpen()) { updateInventory(); } hasInventory = getSpells().size() + getMaterialNames().size() > 1; return addedNew; } @SuppressWarnings("deprecation") public boolean addMaterial(Material material, byte data, boolean makeActive, boolean force) { if (!modifiable && !force) return false; if (isInventoryOpen()) { saveInventory(); } Integer id = material.getId(); String materialString = id.toString(); if (material == EraseMaterial) { materialString = "0"; } else if (material == CopyMaterial) { materialString = "-1"; } materialString += ":" + data; return addMaterial(materialString, makeActive, force); } public boolean removeSpell(String spellName) { if (!modifiable) return false; if (isInventoryOpen()) { saveInventory(); } if (spellName.equals(activeSpell)) { activeSpell = null; } List<Inventory> allInventories = getAllInventories(); boolean found = false; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (itemStack != null && itemStack.getType() != Material.AIR && !isWand(itemStack) && isSpell(itemStack)) { if (getSpell(itemStack).equals(spellName)) { found = true; inventory.setItem(index, null); } else if (activeSpell == null) { activeSpell = getSpell(itemStack); } if (found && activeSpell != null) { break; } } } } updateInventoryNames(true); updateName(); updateLore(); saveState(); if (isInventoryOpen()) { updateInventory(); } return found; } public boolean addSpell(String spellName, boolean makeActive) { if (!modifiable) return false; if (isInventoryOpen()) { saveInventory(); } boolean addedNew = !hasSpell(spellName); if (addedNew) { addToInventory(createSpellItem(spellName)); } if (activeSpell == null || activeSpell.length() == 0 || makeActive) { activeSpell = spellName; } hasInventory = getSpells().size() + getMaterialNames().size() > 1; updateInventoryNames(true); updateName(); updateLore(); saveState(); if (isInventoryOpen()) { updateInventory(); } return addedNew; } public boolean addSpell(String spellName) { return addSpell(spellName, false); } private String getActiveWandName(Spell spell, String materialName) { // Build wand name ChatColor wandColor = modifiable ? ChatColor.AQUA : ChatColor.RED; String name = wandColor + wandName; // Add active spell to description if (spell != null) { if (materialName != null) { materialName = materialName.replace('_', ' '); name = ChatColor.GOLD + spell.getName() + ChatColor.GRAY + " " + materialName + ChatColor.WHITE + " (" + wandColor + wandName + ChatColor.WHITE + ")"; } else { name = ChatColor.GOLD + spell.getName() + ChatColor.WHITE + " (" + wandColor + wandName + ChatColor.WHITE + ")"; } } int remaining = getRemainingUses(); if (remaining > 0) { name = name + " : " + ChatColor.RED + Messages.get("wand.uses_remaining_brief").replace("$count", ((Integer)remaining).toString()); } return name; } @SuppressWarnings("deprecation") private String getActiveWandName(Spell spell) { String[] pieces = StringUtils.split(activeMaterial, ":"); String materialName = null; if (spell != null && spell.usesMaterial() && !spell.hasMaterialOverride() && pieces.length > 0 && pieces[0].length() > 0) { int materialId = Integer.parseInt(pieces[0]); if (materialId == 0) { materialName = "erase"; } else if (materialId == -1) { materialName = "copy"; } else { Material material = Material.getMaterial(materialId); materialName = material.name().toLowerCase();; } } return getActiveWandName(spell, materialName); } private String getMaterialName(Material material) { return getMaterialName(material, (byte)0); } @SuppressWarnings("deprecation") private String getMaterialName(Material material, byte data) { String materialName = null; if (material == EraseMaterial) { materialName = "erase"; } else if (material == CopyMaterial) { materialName = "copy"; } else { materialName = material.name().toLowerCase(); // I started doing this the "right" way by looking at MaterialData // But I don't feel like waiting for Bukkit to update their classes. // This also seems super ugly and messy.. if this is the replacement for "magic numbers", count me out :P /* Class<? extends MaterialData> materialData = material.getData(); if (Dye.class.isAssignableFrom(materialData)) { Dye dye = new Dye(material, data); materialName += " " + dye.getColor().name(); } else if (Dye.class.isAssignableFrom(materialData)) { Dye dye = new Dye(material, data); materialName += " " + dye.getColor().name(); } */ if (material == Material.CARPET || material == Material.STAINED_GLASS || material == Material.STAINED_CLAY || material == Material.STAINED_GLASS_PANE || material == Material.WOOL) { // Note that getByDyeData doesn't work for stained glass or clay. Kind of misleading? DyeColor color = DyeColor.getByWoolData(data); materialName = color.name().toLowerCase().replace('_', ' ') + " " + materialName; } else if (material == Material.WOOD || material == Material.LOG || material == Material.SAPLING || material == Material.LEAVES) { TreeSpecies treeSpecies = TreeSpecies.getByData(data); materialName = treeSpecies.name().toLowerCase().replace('_', ' ') + " " + materialName; } } materialName = materialName.replace('_', ' '); return materialName; } private String getActiveWandName(Material material) { Spell spell = spells.getSpell(activeSpell); String materialName = null; if (spell != null && spell.usesMaterial() && !spell.hasMaterialOverride() && material != null) { materialName = getMaterialName(material); } return getActiveWandName(spell, materialName); } private String getActiveWandName() { Spell spell = null; if (hasInventory) { spell = spells.getSpell(activeSpell); } return getActiveWandName(spell); } public void updateName(boolean isActive) { ItemMeta meta = item.getItemMeta(); meta.setDisplayName(isActive ? getActiveWandName() : wandName); item.setItemMeta(meta); // Reset Enchantment glow InventoryUtils.addGlow(item); // The all-important last step of restoring the meta state, something // the Anvil will blow away. saveState(); } private void updateName() { updateName(true); } private String getLevelString(String prefix, float amount) { String suffix = ""; if (amount >= 1) { suffix = Messages.get("wand.enchantment_level_max"); } else if (amount > 0.8) { suffix = Messages.get("wand.enchantment_level_5"); } else if (amount > 0.6) { suffix = Messages.get("wand.enchantment_level_4"); } else if (amount > 0.4) { suffix = Messages.get("wand.enchantment_level_3"); } else if (amount > 0.2) { suffix = Messages.get("wand.enchantment_level_2"); } else { suffix = Messages.get("wand.enchantment_level_1"); } return prefix + " " + suffix; } protected static String convertToHTML(String line) { int tagCount = 1; line = "<span style=\"color:white\">" + line; for (ChatColor c : ChatColor.values()) { tagCount += StringUtils.countMatches(line, c.toString()); String replaceStyle = ""; if (c == ChatColor.ITALIC) { replaceStyle = "font-style: italic"; } else if (c == ChatColor.BOLD) { replaceStyle = "font-weight: bold"; } else if (c == ChatColor.UNDERLINE) { replaceStyle = "text-decoration: underline"; } else { String color = c.name().toLowerCase().replace("_", ""); if (c == ChatColor.LIGHT_PURPLE) { color = "mediumpurple"; } replaceStyle = "color:" + color; } line = line.replace(c.toString(), "<span style=\"" + replaceStyle + "\">"); } for (int i = 0; i < tagCount; i++) { line += "</span>"; } return line; } public String getHTMLDescription() { Collection<String> rawLore = getLore(); Collection<String> lore = new ArrayList<String>(); lore.add("<h2>" + convertToHTML(getActiveWandName()) + "</h2>"); for (String line : rawLore) { lore.add(convertToHTML(line)); } return "<div style=\"background-color: black; margin: 8px; padding: 8px\">" + StringUtils.join(lore, "<br/>") + "</div>"; } private List<String> getLore() { return getLore(getSpells().size(), getMaterialNames().size()); } private List<String> getLore(int spellCount, int materialCount) { List<String> lore = new ArrayList<String>(); Spell spell = spells.getSpell(activeSpell); if (spell != null && spellCount == 1 && materialCount <= 1) { addSpellLore(spell, lore); } else { if (description.length() > 0) { lore.add(ChatColor.ITALIC + "" + ChatColor.GREEN + description); } lore.add(Messages.get("wand.spell_count").replace("$count", ((Integer)spellCount).toString())); if (materialCount > 0) { lore.add(Messages.get("wand.material_count").replace("$count", ((Integer)materialCount).toString())); } } int remaining = getRemainingUses(); if (remaining > 0) { lore.add(ChatColor.RED + Messages.get("wand.uses_remaining").replace("$count", ((Integer)remaining).toString())); } if (xpRegeneration > 0) { lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + Messages.get("wand.mana_amount").replace("$amount", ((Integer)xpMax).toString())); lore.add(ChatColor.RESET + "" + ChatColor.LIGHT_PURPLE + getLevelString(Messages.get("wand.mana_regeneration"), xpRegeneration / WandLevel.maxXpRegeneration)); } if (costReduction > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.cost_reduction"), costReduction)); if (cooldownReduction > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.cooldown_reduction"), cooldownReduction)); if (power > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.power"), power)); if (speedIncrease > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.haste"), speedIncrease / WandLevel.maxSpeedIncrease)); if (damageReduction > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection"), damageReduction)); if (damageReduction < 1) { if (damageReductionPhysical > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_physical"), damageReductionPhysical)); if (damageReductionProjectiles > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_projectile"), damageReductionProjectiles)); if (damageReductionFalling > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_fall"), damageReductionFalling)); if (damageReductionFire > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_fire"), damageReductionFire)); if (damageReductionExplosions > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_blast"), damageReductionExplosions)); } if (healthRegeneration > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.health_regeneration"), healthRegeneration / WandLevel.maxRegeneration)); if (hungerRegeneration > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.hunger_regeneration"), hungerRegeneration / WandLevel.maxRegeneration)); return lore; } private void updateLore() { ItemMeta meta = item.getItemMeta(); List<String> lore = getLore(); meta.setLore(lore); item.setItemMeta(meta); InventoryUtils.addGlow(item); // Reset spell list and wand config saveState(); } public int getRemainingUses() { return uses; } public void makeEnchantable(boolean enchantable) { item.setType(enchantable ? EnchantableWandMaterial : WandMaterial); updateName(); } public static boolean hasActiveWand(Player player) { ItemStack activeItem = player.getInventory().getItemInHand(); return isWand(activeItem); } public static Wand getActiveWand(Spells spells, Player player) { ItemStack activeItem = player.getInventory().getItemInHand(); if (isWand(activeItem)) { return new Wand(spells, activeItem); } return null; } public static boolean isWand(ItemStack item) { // Special-case here for porting old wands. Could be removed eventually. return item != null && (item.getType() == WandMaterial || item.getType() == EnchantableWandMaterial) && (InventoryUtils.hasMeta(item, "wand") || InventoryUtils.hasMeta(item, "magic_wand")); } public static boolean isSpell(ItemStack item) { return item != null && item.getType() != WandMaterial && InventoryUtils.hasMeta(item, "spell"); } public static String getSpell(ItemStack item) { if (!isSpell(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); return InventoryUtils.getMeta(spellNode, "key"); } public void updateInventoryNames(boolean activeNames) { if (activePlayer == null || !isInventoryOpen()) return; ItemStack[] contents = activePlayer.getPlayer().getInventory().getContents(); for (ItemStack item : contents) { if (item == null || item.getType() == Material.AIR || isWand(item)) continue; updateInventoryName(item, activeNames); } } protected void updateInventoryName(ItemStack item, boolean activeName) { if (isSpell(item)) { Spell spell = activePlayer.getSpell(getSpell(item)); if (spell != null) { updateSpellName(item, spell, activeName); } } else { updateMaterialName(item, activeName); } } protected void updateSpellName(ItemStack itemStack, Spell spell, boolean activeName) { ItemMeta meta = itemStack.getItemMeta(); if (activeName) { meta.setDisplayName(getActiveWandName(spell)); } else { meta.setDisplayName(ChatColor.GOLD + spell.getName()); } List<String> lore = new ArrayList<String>(); addSpellLore(spell, lore); meta.setLore(lore); itemStack.setItemMeta(meta); InventoryUtils.addGlow(itemStack); Object spellNode = InventoryUtils.createNode(itemStack, "spell"); InventoryUtils.setMeta(spellNode, "key", spell.getKey()); } protected void updateMaterialName(ItemStack itemStack, boolean activeName) { ItemMeta meta = itemStack.getItemMeta(); if (activeName) { meta.setDisplayName(getActiveWandName(itemStack.getType())); } else { meta.setDisplayName(getMaterialName(itemStack.getType())); } itemStack.setItemMeta(meta); } @SuppressWarnings("deprecation") private void updateInventory() { if (activePlayer == null) return; if (!isInventoryOpen()) return; if (activePlayer.getPlayer() == null) return; if (!activePlayer.hasStoredInventory()) return; // Clear the player's inventory Player player = activePlayer.getPlayer(); PlayerInventory playerInventory = player.getInventory(); playerInventory.clear(); // First add the wand and check the hotbar for conflicts int currentSlot = playerInventory.getHeldItemSlot(); ItemStack existingHotbar = hotbar.getItem(currentSlot); if (existingHotbar != null && existingHotbar.getType() != Material.AIR && !isWand(existingHotbar)) { addToInventory(existingHotbar); hotbar.setItem(currentSlot, null); } playerInventory.setItem(currentSlot, item); // Set hotbar for (int hotbarSlot = 0; hotbarSlot < hotbarSize; hotbarSlot++) { if (hotbarSlot != currentSlot) { playerInventory.setItem(hotbarSlot, hotbar.getItem(hotbarSlot)); } } // Set inventory from current page if (openInventoryPage < inventories.size()) { Inventory inventory = inventories.get(openInventoryPage); ItemStack[] contents = inventory.getContents(); for (int i = 0; i < contents.length; i++) { playerInventory.setItem(i + hotbarSize, contents[i]); } } updateName(); player.updateInventory(); } protected void addSpellLore(Spell spell, List<String> lore) { String description = spell.getDescription(); String usage = spell.getUsage(); if (description != null && description.length() > 0) { lore.add(description); } if (usage != null && usage.length() > 0) { lore.add(usage); } List<CastingCost> costs = spell.getCosts(); if (costs != null) { for (CastingCost cost : costs) { if (cost.hasCosts(this)) { lore.add(ChatColor.YELLOW + Messages.get("wand.costs_description").replace("$description", cost.getFullDescription(this))); } } } } protected Inventory getOpenInventory() { while (openInventoryPage >= inventories.size()) { inventories.add(InventoryUtils.createInventory(null, inventorySize, "Wand")); } return inventories.get(openInventoryPage); } public void saveInventory() { if (activePlayer == null) return; if (activePlayer == null) return; if (!isInventoryOpen()) return; if (activePlayer.getPlayer() == null) return; if (!activePlayer.hasStoredInventory()) return; // Fill in the hotbar Player player = activePlayer.getPlayer(); PlayerInventory playerInventory = player.getInventory(); for (int i = 0; i < hotbarSize; i++) { ItemStack playerItem = playerInventory.getItem(i); if (isWand(playerItem)) { playerItem = null; } hotbar.setItem(i, playerItem); } // Fill in the active inventory page Inventory openInventory = getOpenInventory(); for (int i = 0; i < openInventory.getSize(); i++) { openInventory.setItem(i, playerInventory.getItem(i + hotbarSize)); } saveState(); } public static boolean isActive(Player player) { ItemStack activeItem = player.getInventory().getItemInHand(); return isWand(activeItem); } protected void randomize(int level, boolean additive) { if (!wandTemplates.containsKey("random")) return; if (!additive) { wandName = Messages.get("wands.random.name", wandName); } WandLevel.randomizeWand(this, additive, level); } public static Wand createWand(Spells spells, String templateName) { Wand wand = new Wand(spells); String wandName = Messages.get("wand.default_name"); String wandDescription = ""; // Check for default wand if ((templateName == null || templateName.length() == 0) && wandTemplates.containsKey("default")) { templateName = "default"; } // See if there is a template with this key if (templateName != null && templateName.length() > 0) { if ((templateName.equals("random") || templateName.startsWith("random(")) && wandTemplates.containsKey("random")) { int level = 1; if (!templateName.equals("random")) { String randomLevel = templateName.substring(templateName.indexOf('(') + 1, templateName.length() - 1); level = Integer.parseInt(randomLevel); } ConfigurationNode randomTemplate = wandTemplates.get("random"); wand.modifiable = (boolean)randomTemplate.getBoolean("modifiable", true); wand.randomize(level, false); return wand; } if (!wandTemplates.containsKey(templateName)) { return null; } ConfigurationNode wandConfig = wandTemplates.get(templateName); wandName = Messages.get("wands." + templateName + ".name", wandName); wandDescription = Messages.get("wands." + templateName + ".description", wandDescription); List<Object> spellList = wandConfig.getList("spells"); if (spellList != null) { for (Object spellName : spellList) { wand.addSpell((String)spellName); } } List<Object> materialList = wandConfig.getList("materials"); if (materialList != null) { for (Object materialNameAndData : materialList) { String[] materialParts = StringUtils.split((String)materialNameAndData, ':'); String materialName = materialParts[0]; byte data = 0; if (materialParts.length > 1) { data = Byte.parseByte(materialParts[1]); } if (materialName.equals("erase")) { wand.addMaterial(EraseMaterial, (byte)0, false); } else if (materialName.equals("copy") || materialName.equals("clone")) { wand.addMaterial(CopyMaterial, (byte)0, false); } else { wand.addMaterial(ConfigurationNode.toMaterial(materialName), data, false); } } } wand.configureProperties(wandConfig); } wand.setDescription(wandDescription); wand.setName(wandName); return wand; } public void add(Wand other) { if (!modifiable || !other.modifiable) return; costReduction = Math.max(costReduction, other.costReduction); power = Math.max(power, other.power); damageReduction = Math.max(damageReduction, other.damageReduction); damageReductionPhysical = Math.max(damageReductionPhysical, other.damageReductionPhysical); damageReductionProjectiles = Math.max(damageReductionProjectiles, other.damageReductionProjectiles); damageReductionFalling = Math.max(damageReductionFalling, other.damageReductionFalling); damageReductionFire = Math.max(damageReductionFire, other.damageReductionFire); damageReductionExplosions = Math.max(damageReductionExplosions, other.damageReductionExplosions); xpRegeneration = Math.max(xpRegeneration, other.xpRegeneration); xpMax = Math.max(xpMax, other.xpMax); xp = Math.max(xp, other.xp); healthRegeneration = Math.max(healthRegeneration, other.healthRegeneration); hungerRegeneration = Math.max(hungerRegeneration, other.hungerRegeneration); speedIncrease = Math.max(speedIncrease, other.speedIncrease); // Mix colors? if (effectColor == 0) { effectColor = other.effectColor; } else if (other.effectColor != 0){ Color color1 = Color.fromBGR(effectColor); Color color2 = Color.fromBGR(other.effectColor); Color newColor = color1.mixColors(color2); effectColor = newColor.asRGB(); } effectColor = Math.max(effectColor, other.effectColor); // Eliminate limited-use wands if (uses == 0 || other.uses == 0) { uses = 0; } else { // Otherwise add them uses = uses + other.uses; } // Add spells Set<String> spells = other.getSpells(); for (String spell : spells) { addSpell(spell, false); } // Add materials Set<String> materials = other.getMaterialNames(); for (String material : materials) { addMaterial(material, false, true); } saveState(); updateName(); updateLore(); } public void configureProperties(ConfigurationNode wandConfig) { configureProperties(wandConfig, false); } public void configureProperties(ConfigurationNode wandConfig, boolean safe) { modifiable = (boolean)wandConfig.getBoolean("modifiable", modifiable); float _costReduction = (float)wandConfig.getDouble("cost_reduction", costReduction); costReduction = safe ? Math.max(_costReduction, costReduction) : _costReduction; float _cooldownReduction = (float)wandConfig.getDouble("cooldown_reduction", cooldownReduction); cooldownReduction = safe ? Math.max(_cooldownReduction, cooldownReduction) : _cooldownReduction; float _power = (float)wandConfig.getDouble("power", power); power = safe ? Math.max(_power, power) : _power; float _damageReduction = (float)wandConfig.getDouble("protection", damageReduction); damageReduction = safe ? Math.max(_damageReduction, damageReduction) : _damageReduction; float _damageReductionPhysical = (float)wandConfig.getDouble("protection_physical", damageReductionPhysical); damageReductionPhysical = safe ? Math.max(_damageReductionPhysical, damageReductionPhysical) : _damageReductionPhysical; float _damageReductionProjectiles = (float)wandConfig.getDouble("protection_projectiles", damageReductionProjectiles); damageReductionProjectiles = safe ? Math.max(_damageReductionProjectiles, damageReductionPhysical) : _damageReductionProjectiles; float _damageReductionFalling = (float)wandConfig.getDouble("protection_falling", damageReductionFalling); damageReductionFalling = safe ? Math.max(_damageReductionFalling, damageReductionFalling) : _damageReductionFalling; float _damageReductionFire = (float)wandConfig.getDouble("protection_fire", damageReductionFire); damageReductionFire = safe ? Math.max(_damageReductionFire, damageReductionFire) : _damageReductionFire; float _damageReductionExplosions = (float)wandConfig.getDouble("protection_explosions", damageReductionExplosions); damageReductionExplosions = safe ? Math.max(_damageReductionExplosions, damageReductionExplosions) : _damageReductionExplosions; int _xpRegeneration = wandConfig.getInt("xp_regeneration", xpRegeneration); xpRegeneration = safe ? Math.max(_xpRegeneration, xpRegeneration) : _xpRegeneration; int _xpMax = wandConfig.getInt("xp_max", xpMax); xpMax = safe ? Math.max(_xpMax, xpMax) : _xpMax; int _xp = wandConfig.getInt("xp", xp); xp = safe ? Math.max(_xp, xp) : _xp; int _healthRegeneration = wandConfig.getInt("health_regeneration", healthRegeneration); healthRegeneration = safe ? Math.max(_healthRegeneration, healthRegeneration) : _healthRegeneration; int _hungerRegeneration = wandConfig.getInt("hunger_regeneration", hungerRegeneration); hungerRegeneration = safe ? Math.max(_hungerRegeneration, hungerRegeneration) : _hungerRegeneration; int _uses = wandConfig.getInt("uses", uses); uses = safe ? Math.max(_uses, uses) : _uses; effectColor = Integer.parseInt(wandConfig.getString("effect_color", "0"), 16); // Make sure to adjust the player's walk speed if it changes and this wand is active. float oldWalkSpeedIncrease = speedIncrease; speedIncrease = (float)wandConfig.getDouble("haste", speedIncrease); if (activePlayer != null && speedIncrease != oldWalkSpeedIncrease) { Player player = activePlayer.getPlayer(); player.setWalkSpeed(defaultWalkSpeed + speedIncrease); player.setFlySpeed(defaultFlySpeed + speedIncrease); } saveState(); updateName(); updateLore(); } public static void reset(Plugin plugin) { File dataFolder = plugin.getDataFolder(); File propertiesFile = new File(dataFolder, propertiesFileName); propertiesFile.delete(); } public static void load(Plugin plugin) { // Load properties file with wand templates File dataFolder = plugin.getDataFolder(); File oldDefaults = new File(dataFolder, propertiesFileNameDefaults); oldDefaults.delete(); plugin.getLogger().info("Overwriting file " + propertiesFileNameDefaults); plugin.saveResource(propertiesFileNameDefaults, false); File propertiesFile = new File(dataFolder, propertiesFileName); if (!propertiesFile.exists()) { plugin.getLogger().info("Loading default wands from " + propertiesFileNameDefaults); loadProperties(plugin.getResource(propertiesFileNameDefaults)); } else { plugin.getLogger().info("Loading wands from " + propertiesFile.getName()); loadProperties(propertiesFile); } } private static void loadProperties(File propertiesFile) { loadProperties(new Configuration(propertiesFile)); } private static void loadProperties(InputStream properties) { loadProperties(new Configuration(properties)); } private static void loadProperties(Configuration properties) { properties.load(); wandTemplates.clear(); ConfigurationNode wandList = properties.getNode("wands"); if (wandList == null) return; List<String> wandKeys = wandList.getKeys(); for (String key : wandKeys) { ConfigurationNode wandNode = wandList.getNode(key); wandNode.setProperty("key", key); wandTemplates.put(key, wandNode); if (key.equals("random")) { WandLevel.mapLevels(wandNode); } } } public static Collection<ConfigurationNode> getWandTemplates() { return wandTemplates.values(); } @SuppressWarnings("deprecation") private void updateActiveMaterial() { if (activePlayer == null) return; if (activeMaterial == null) { activePlayer.clearBuildingMaterial(); } else { String[] pieces = StringUtils.split(activeMaterial, ":"); if (pieces.length > 0) { byte data = 0; if (pieces.length > 1) { data = Byte.parseByte(pieces[1]); } int materialId = Integer.parseInt(pieces[0]); Material material = null; if (materialId == 0) { material = EraseMaterial; } else if (materialId == -1) { material = CopyMaterial; } else { material = Material.getMaterial(materialId); } activePlayer.setBuildingMaterial(material, data); } } } public void toggleInventory() { if (!hasInventory) { return; } if (!isInventoryOpen()) { openInventory(); } else { closeInventory(); } } @SuppressWarnings("deprecation") public void cycleInventory() { if (!hasInventory) { return; } if (isInventoryOpen()) { saveInventory(); openInventoryPage = (openInventoryPage + 1) % inventories.size(); updateInventory(); if (activePlayer != null && inventories.size() > 1) { activePlayer.playSound(Sound.CHEST_OPEN, 0.3f, 1.5f); activePlayer.getPlayer().updateInventory(); } } } @SuppressWarnings("deprecation") private void openInventory() { if (activePlayer == null) return; if (activePlayer.hasStoredInventory()) return; if (activePlayer.storeInventory()) { inventoryIsOpen = true; activePlayer.playSound(Sound.CHEST_OPEN, 0.4f, 0.2f); updateInventory(); activePlayer.getPlayer().updateInventory(); } } @SuppressWarnings("deprecation") public void closeInventory() { if (!isInventoryOpen()) return; saveInventory(); inventoryIsOpen = false; if (activePlayer != null) { activePlayer.playSound(Sound.CHEST_CLOSE, 0.4f, 0.2f); activePlayer.restoreInventory(); activePlayer.getPlayer().updateInventory(); ItemStack newWandItem = activePlayer.getPlayer().getInventory().getItemInHand(); if (isWand(newWandItem)) { item = newWandItem; updateName(); } } saveState(); } public void activate(PlayerSpells playerSpells) { if (owner.length() == 0) { takeOwnership(playerSpells.getPlayer()); } activePlayer = playerSpells; Player player = activePlayer.getPlayer(); if (speedIncrease > 0) { try { player.setWalkSpeed(defaultWalkSpeed + speedIncrease); player.setFlySpeed(defaultFlySpeed + speedIncrease); } catch(Exception ex2) { try { player.setWalkSpeed(defaultWalkSpeed); player.setFlySpeed(defaultFlySpeed); } catch(Exception ex) { } } } activePlayer.setActiveWand(this); if (xpRegeneration > 0) { storedXpLevel = player.getLevel(); storedXpProgress = player.getExp(); storedXp = 0; updateMana(); } updateActiveMaterial(); updateName(); if (effectColor != 0) { InventoryUtils.addPotionEffect(player, effectColor); } } protected void updateMana() { if (activePlayer != null && xpMax > 0 && xpRegeneration > 0) { Player player = activePlayer.getPlayer(); player.setLevel(0); player.setExp((float)xp / (float)xpMax); } } public boolean isInventoryOpen() { return activePlayer != null && inventoryIsOpen; } public void deactivate() { if (activePlayer == null) return; saveState(); if (effectColor > 0) { InventoryUtils.removePotionEffect(activePlayer.getPlayer()); } // This is a tying wands together with other spells, potentially // But with the way the mana system works, this seems like the safest route. activePlayer.deactivateAllSpells(); if (isInventoryOpen()) { closeInventory(); } // Extra just-in-case activePlayer.restoreInventory(); if (xpRegeneration > 0) { activePlayer.player.setExp(storedXpProgress); activePlayer.player.setLevel(storedXpLevel); activePlayer.player.giveExp(storedXp); storedXp = 0; storedXpProgress = 0; storedXpLevel = 0; } if (speedIncrease > 0) { try { activePlayer.getPlayer().setWalkSpeed(defaultWalkSpeed); activePlayer.getPlayer().setFlySpeed(defaultFlySpeed); } catch(Exception ex) { } } activePlayer.setActiveWand(null); activePlayer = null; } public Spell getActiveSpell() { if (activePlayer == null) return null; return activePlayer.getSpell(activeSpell); } public boolean cast() { Spell spell = getActiveSpell(); if (spell != null) { if (spell.cast()) { use(); return true; } } return false; } @SuppressWarnings("deprecation") protected void use() { if (activePlayer == null) return; if (uses > 0) { uses--; if (uses <= 0) { Player player = activePlayer.getPlayer(); activePlayer.playSound(Sound.ITEM_BREAK, 1.0f, 0.8f); PlayerInventory playerInventory = player.getInventory(); playerInventory.setItemInHand(new ItemStack(Material.AIR, 1)); player.updateInventory(); deactivate(); } else { updateName(); updateLore(); saveState(); } } } public void onPlayerExpChange(PlayerExpChangeEvent event) { if (activePlayer == null) return; if (xpRegeneration > 0) { storedXp += event.getAmount(); event.setAmount(0); } } public void processRegeneration() { if (activePlayer == null) return; Player player = activePlayer.getPlayer(); if (xpRegeneration > 0) { xp = Math.min(xpMax, xp + xpRegeneration); updateMana(); } double maxHealth = player.getMaxHealth(); if (healthRegeneration > 0 && player.getHealth() < maxHealth) { player.setHealth(Math.min(maxHealth, player.getHealth() + healthRegeneration)); } double maxFoodLevel = 20; if (hungerRegeneration > 0 && player.getFoodLevel() < maxFoodLevel) { player.setExhaustion(0); player.setFoodLevel(Math.min(20, player.getFoodLevel() + hungerRegeneration)); } if (damageReductionFire > 0 && player.getFireTicks() > 0) { player.setFireTicks(0); } } @Override public boolean equals(Object other) { if (other == null) return false; if (!(other instanceof Wand)) return false; Wand otherWand = ((Wand)other); if (this.id == null || otherWand.id == null) return false; return otherWand.id.equals(this.id); } public Spells getMaster() { return spells; } public void cycleSpells() { Set<String> spellsSet = getSpells(); String[] spells = (String[])spellsSet.toArray(); if (spells.length == 0) return; if (activeSpell == null) { activeSpell = spells[0].split("@")[0]; return; } int spellIndex = 0; for (int i = 0; i < spells.length; i++) { if (spells[i].split("@")[0].equals(activeSpell)) { spellIndex = i; break; } } spellIndex = (spellIndex + 1) % spells.length; setActiveSpell(spells[spellIndex].split("@")[0]); } public void cycleMaterials() { Set<String> materialsSet = getMaterialNames(); String[] materials = (String[])materialsSet.toArray(); if (materials.length == 0) return; if (activeMaterial == null) { activeMaterial = materials[0].split("@")[0]; return; } int materialIndex = 0; for (int i = 0; i < materials.length; i++) { if (materials[i].split("@")[0].equals(activeMaterial)) { materialIndex = i; break; } } materialIndex = (materialIndex + 1) % materials.length; setActiveMaterial(materials[materialIndex].split("@")[0]); } public boolean hasExperience() { return xpRegeneration > 0; } public void organizeInventory() { if (activePlayer == null) return; if (!isInventoryOpen()) return; WandOrganizer organizer = new WandOrganizer(this); organizer.organize(); openInventoryPage = 0; updateInventory(); saveState(); } public PlayerSpells getActivePlayer() { return activePlayer; } public String getId() { return this.id; } protected void clearInventories() { inventories.clear(); } }
src/main/java/com/elmakers/mine/bukkit/plugins/magic/Wand.java
package com.elmakers.mine.bukkit.plugins.magic; import java.io.File; import java.io.InputStream; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.TreeSpecies; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerExpChangeEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; import com.elmakers.mine.bukkit.utilities.InventoryUtils; import com.elmakers.mine.bukkit.utilities.Messages; import com.elmakers.mine.bukkit.utilities.borrowed.Configuration; import com.elmakers.mine.bukkit.utilities.borrowed.ConfigurationNode; public class Wand implements CostReducer { protected final static int inventorySize = 27; protected final static int inventoryOrganizeSize = 16; protected final static int inventoryOrganizeNewGroupSize = 8; protected final static int hotbarSize = 9; private ItemStack item; private Spells spells; private PlayerSpells activePlayer; // Cached state private String id; private Inventory hotbar; private List<Inventory> inventories; private String activeSpell = ""; private String activeMaterial = ""; private String wandName = ""; private String description = ""; private String owner = ""; private float costReduction = 0; private float cooldownReduction = 0; private float damageReduction = 0; private float damageReductionPhysical = 0; private float damageReductionProjectiles = 0; private float damageReductionFalling = 0; private float damageReductionFire = 0; private float damageReductionExplosions = 0; private float power = 0; private boolean hasInventory = false; private boolean modifiable = true; private int uses = 0; private int xp = 0; private int xpRegeneration = 0; private int xpMax = 50; private int healthRegeneration = 0; private int hungerRegeneration = 0; private int effectColor = 0; private float defaultWalkSpeed = 0.2f; private float defaultFlySpeed = 0.1f; private float speedIncrease = 0; private int storedXpLevel = 0; private int storedXp = 0; private float storedXpProgress = 0; private static DecimalFormat floatFormat = new DecimalFormat("#.###"); public static Material WandMaterial = Material.BLAZE_ROD; public static Material EnchantableWandMaterial = Material.WOOD_SWORD; public static Material EraseMaterial = Material.SULPHUR; public static Material CopyMaterial = Material.PUMPKIN_SEEDS; // Wand configurations protected static Map<String, ConfigurationNode> wandTemplates = new HashMap<String, ConfigurationNode>(); private static final String propertiesFileName = "wands.yml"; private static final String propertiesFileNameDefaults = "wands.defaults.yml"; // Inventory functionality int openInventoryPage = 0; boolean inventoryIsOpen = false; private Wand() { hotbar = InventoryUtils.createInventory(null, 9, "Wand"); inventories = new ArrayList<Inventory>(); } public Wand(Spells spells) { this(); this.spells = spells; item = new ItemStack(WandMaterial); // This will make the Bukkit ItemStack into a real ItemStack with NBT data. item = InventoryUtils.getCopy(item); ItemMeta itemMeta = item.getItemMeta(); item.setItemMeta(itemMeta); InventoryUtils.addGlow(item); id = UUID.randomUUID().toString(); wandName = Messages.get("wand.default_name"); updateName(); saveState(); } public Wand(Spells spells, ItemStack item) { this(); this.item = item; this.spells = spells; loadState(); } public void setActiveSpell(String activeSpell) { this.activeSpell = activeSpell; updateName(); updateInventoryNames(true); saveState(); } @SuppressWarnings("deprecation") public void setActiveMaterial(Material material, byte data) { String materialKey = ""; if (material == CopyMaterial) { materialKey = "-1:0"; } else if (material == EraseMaterial) { materialKey = "0:0"; } else { materialKey = material.getId() + ":" + data; } setActiveMaterial(materialKey); } protected void setActiveMaterial(String materialKey) { this.activeMaterial = materialKey; updateName(); updateActiveMaterial(); updateInventoryNames(true); saveState(); } public int getXpRegeneration() { return xpRegeneration; } public int getXpMax() { return xpMax; } public int getExperience() { return xp; } public void removeExperience(int amount) { xp = Math.max(0, xp - amount); updateMana(); } public int getHealthRegeneration() { return healthRegeneration; } public int getHungerRegeneration() { return hungerRegeneration; } public float getCostReduction() { return costReduction; } public boolean isModifiable() { return modifiable; } public boolean usesMana() { return xpMax > 0 && xpRegeneration > 0; } public float getCooldownReduction() { return cooldownReduction; } public boolean getHasInventory() { return hasInventory; } public float getPower() { return power; } public float getDamageReduction() { return damageReduction; } public float getDamageReductionPhysical() { return damageReductionPhysical; } public float getDamageReductionProjectiles() { return damageReductionProjectiles; } public float getDamageReductionFalling() { return damageReductionFalling; } public float getDamageReductionFire() { return damageReductionFire; } public float getDamageReductionExplosions() { return damageReductionExplosions; } public int getUses() { return uses; } public String getName() { return wandName; } public String getDescription() { return description; } public String getOwner() { return owner; } protected void setName(String name) { wandName = name; updateName(); } protected void setDescription(String description) { this.description = description; updateLore(); } protected void takeOwnership(Player player) { owner = player.getName(); } public void takeOwnership(Player player, String name, boolean updateDescription) { setName(name); takeOwnership(player); if (updateDescription) { setDescription(Messages.get("wand.owner_description", "$name's Wand").replace("$name", owner)); } } public ItemStack getItem() { return item; } public void setItem(ItemStack item) { this.item = item; } protected List<Inventory> getAllInventories() { List<Inventory> allInventories = new ArrayList<Inventory>(inventories.size() + 1); allInventories.add(hotbar); allInventories.addAll(inventories); return allInventories; } protected Set<String> getSpells() { return getSpells(false); } protected Set<String> getSpells(boolean includePositions) { Set<String> spellNames = new TreeSet<String>(); List<Inventory> allInventories = getAllInventories(); int index = 0; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int i = 0; i < items.length; i++) { if (items[i] != null && !isWand(items[i])) { if (isSpell(items[i])) { String spellName = getSpell(items[i]); if (includePositions) { spellName += "@" + index; } spellNames.add(spellName); } } index++; } } return spellNames; } protected String getSpellString() { return StringUtils.join(getSpells(true), "|"); } protected Set<String> getMaterialNames() { return getMaterialNames(false); } protected static String getMaterialKey(ItemStack itemStack) { return getMaterialKey(itemStack, null); } @SuppressWarnings("deprecation") protected static String getMaterialKey(ItemStack itemStack, Integer index) { if (itemStack == null || isSpell(itemStack) || isWand(itemStack)) { return null; } Material material = itemStack.getType(); if (material == Material.AIR) { return null; } String materialKey = material.getId() + ":" + itemStack.getData().getData(); if (material == EraseMaterial) { materialKey = "0:0"; } else if (material == CopyMaterial) { materialKey = "-1:0"; } if (index != null) { materialKey += "@" + index; } return materialKey; } protected Set<String> getMaterialNames(boolean includePositions) { Set<String> materialNames = new TreeSet<String>(); List<Inventory> allInventories = new ArrayList<Inventory>(inventories.size() + 1); allInventories.add(hotbar); allInventories.addAll(inventories); Integer index = 0; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int i = 0; i < items.length; i++) { String materialKey = getMaterialKey(items[i], includePositions ? index : null); if (materialKey != null) { materialNames.add(materialKey); } index++; } } return materialNames; } protected String getMaterialString() { return StringUtils.join(getMaterialNames(true), "|"); } protected Integer parseSlot(String[] pieces) { Integer slot = null; if (pieces.length > 0) { try { slot = Integer.parseInt(pieces[1]); } catch (Exception ex) { slot = null; } if (slot != null && slot < 0) { slot = null; } } return slot; } protected void addToInventory(ItemStack itemStack) { List<Inventory> allInventories = getAllInventories(); boolean added = false; // Set the wand item Integer selectedItem = null; if (activePlayer != null && activePlayer.getPlayer() != null) { selectedItem = activePlayer.getPlayer().getInventory().getHeldItemSlot(); hotbar.setItem(selectedItem, item); } for (Inventory inventory : allInventories) { HashMap<Integer, ItemStack> returned = inventory.addItem(itemStack); if (returned.size() == 0) { added = true; break; } } if (!added) { Inventory newInventory = InventoryUtils.createInventory(null, inventorySize, "Wand"); newInventory.addItem(itemStack); inventories.add(newInventory); } if (selectedItem != null) { hotbar.setItem(selectedItem, null); } } protected Inventory getInventoryByIndex(int inventoryIndex) { while (inventoryIndex >= inventories.size()) { inventories.add(InventoryUtils.createInventory(null, inventorySize, "Wand")); } return inventories.get(inventoryIndex); } protected Inventory getInventory(Integer slot) { Inventory inventory = hotbar; if (slot >= hotbarSize) { int inventoryIndex = (slot - hotbarSize) / inventorySize; inventory = getInventoryByIndex(inventoryIndex); } return inventory; } protected int getInventorySlot(Integer slot) { if (slot < hotbarSize) { return slot; } return ((slot - hotbarSize) % inventorySize); } protected void addToInventory(ItemStack itemStack, Integer slot) { if (slot == null) { addToInventory(itemStack); return; } Inventory inventory = getInventory(slot); slot = getInventorySlot(slot); ItemStack existing = inventory.getItem(slot); inventory.setItem(slot, itemStack); if (existing != null && existing.getType() != Material.AIR) { addToInventory(existing); } } protected void parseInventoryStrings(String spellString, String materialString) { hotbar.clear(); inventories.clear(); String[] spellNames = StringUtils.split(spellString, "|"); for (String spellName : spellNames) { String[] pieces = spellName.split("@"); Integer slot = parseSlot(pieces); ItemStack itemStack = createSpellItem(pieces[0]); if (itemStack == null) continue; addToInventory(itemStack, slot); } String[] materialNames = StringUtils.split(materialString, "|"); for (String materialName : materialNames) { String[] pieces = materialName.split("@"); Integer slot = parseSlot(pieces); ItemStack itemStack = createMaterialItem(pieces[0]); addToInventory(itemStack, slot); } hasInventory = spellNames.length + materialNames.length > 1; } @SuppressWarnings("deprecation") protected ItemStack createMaterialItem(String materialKey) { String[] nameParts = StringUtils.split(materialKey, ":"); int typeId = Integer.parseInt(nameParts[0]); if (typeId == 0) { typeId = EraseMaterial.getId(); } else if (typeId == -1) { typeId = CopyMaterial.getId(); } byte dataId = nameParts.length > 1 ? Byte.parseByte(nameParts[1]) : 0; return createMaterialItem(typeId, dataId); } protected ItemStack createSpellItem(String spellName) { Spell spell = spells.getSpell(spellName); if (spell == null) return null; if (spell.getMaterial() == null) { spells.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getName() + ", missing material"); } ItemStack itemStack = null; ItemStack originalItemStack = null; try { originalItemStack = new ItemStack(spell.getMaterial(), 1); itemStack = InventoryUtils.getCopy(originalItemStack); } catch (Exception ex) { itemStack = null; } if (itemStack == null) { spells.getPlugin().getLogger().warning("Unable to create spell icon with material " + spell.getMaterial().name()); return originalItemStack; } updateSpellName(itemStack, spell, true); return itemStack; } @SuppressWarnings("deprecation") protected ItemStack createMaterialItem(int typeId, byte dataId) { if (typeId == 0) { typeId = EraseMaterial.getId(); } else if (typeId == -1) { typeId = CopyMaterial.getId(); } ItemStack originalItemStack = new ItemStack(typeId, 1, (short)0, (byte)dataId); ItemStack itemStack = InventoryUtils.getCopy(originalItemStack); if (itemStack == null) { spells.getPlugin().getLogger().warning("Unable to create material icon for id " + typeId + ": " + originalItemStack.getType()); return originalItemStack; } ItemMeta meta = itemStack.getItemMeta(); if (typeId == EraseMaterial.getId()) { typeId = EraseMaterial.getId(); List<String> lore = new ArrayList<String>(); lore.add(Messages.get("wand.erase_material_description")); meta.setLore(lore); } else if (typeId == CopyMaterial.getId()) { typeId = EraseMaterial.getId(); List<String> lore = new ArrayList<String>(); lore.add(Messages.get("wand.copy_material_description")); meta.setLore(lore); } else { List<String> lore = new ArrayList<String>(); Material material = Material.getMaterial(typeId); if (material != null) { lore.add(ChatColor.GRAY + getMaterialName(material, (byte)dataId)); } lore.add(ChatColor.LIGHT_PURPLE + Messages.get("wand.building_material_description")); meta.setLore(lore); } meta.setDisplayName(getActiveWandName(Material.getMaterial(typeId))); itemStack.setItemMeta(meta); return itemStack; } protected void saveState() { Object wandNode = InventoryUtils.createNode(item, "wand"); InventoryUtils.setMeta(wandNode, "id", id); String wandMaterials = getMaterialString(); String wandSpells = getSpellString(); InventoryUtils.setMeta(wandNode, "materials", wandMaterials); InventoryUtils.setMeta(wandNode, "spells", wandSpells); InventoryUtils.setMeta(wandNode, "active_spell", activeSpell); InventoryUtils.setMeta(wandNode, "active_material", activeMaterial); InventoryUtils.setMeta(wandNode, "name", wandName); InventoryUtils.setMeta(wandNode, "description", description); InventoryUtils.setMeta(wandNode, "owner", owner); InventoryUtils.setMeta(wandNode, "cost_reduction", floatFormat.format(costReduction)); InventoryUtils.setMeta(wandNode, "cooldown_reduction", floatFormat.format(cooldownReduction)); InventoryUtils.setMeta(wandNode, "power", floatFormat.format(power)); InventoryUtils.setMeta(wandNode, "protection", floatFormat.format(damageReduction)); InventoryUtils.setMeta(wandNode, "protection_physical", floatFormat.format(damageReductionPhysical)); InventoryUtils.setMeta(wandNode, "protection_projectiles", floatFormat.format(damageReductionProjectiles)); InventoryUtils.setMeta(wandNode, "protection_falling", floatFormat.format(damageReductionFalling)); InventoryUtils.setMeta(wandNode, "protection_fire", floatFormat.format(damageReductionFire)); InventoryUtils.setMeta(wandNode, "protection_explosions", floatFormat.format(damageReductionExplosions)); InventoryUtils.setMeta(wandNode, "haste", floatFormat.format(speedIncrease)); InventoryUtils.setMeta(wandNode, "xp", Integer.toString(xp)); InventoryUtils.setMeta(wandNode, "xp_regeneration", Integer.toString(xpRegeneration)); InventoryUtils.setMeta(wandNode, "xp_max", Integer.toString(xpMax)); InventoryUtils.setMeta(wandNode, "health_regeneration", Integer.toString(healthRegeneration)); InventoryUtils.setMeta(wandNode, "hunger_regeneration", Integer.toString(hungerRegeneration)); InventoryUtils.setMeta(wandNode, "uses", Integer.toString(uses)); InventoryUtils.setMeta(wandNode, "has_inventory", Integer.toString((hasInventory ? 1 : 0))); InventoryUtils.setMeta(wandNode, "modifiable", Integer.toString((modifiable ? 1 : 0))); InventoryUtils.setMeta(wandNode, "effect_color", Integer.toString(effectColor, 16)); } protected void loadState() { Object wandNode = InventoryUtils.getNode(item, "wand"); if (wandNode == null) { spells.getPlugin().getLogger().warning("Found a wand with missing NBT data. This may be an old wand, or something may have wiped its data"); return; } // Don't generate a UUID unless we need to, not sure how expensive that is. id = InventoryUtils.getMeta(wandNode, "id"); id = id == null || id.length() == 0 ? UUID.randomUUID().toString() : id; wandName = InventoryUtils.getMeta(wandNode, "name", wandName); description = InventoryUtils.getMeta(wandNode, "description", description); owner = InventoryUtils.getMeta(wandNode, "owner", owner); String wandMaterials = InventoryUtils.getMeta(wandNode, "materials", ""); String wandSpells = InventoryUtils.getMeta(wandNode, "spells", ""); parseInventoryStrings(wandSpells, wandMaterials); activeSpell = InventoryUtils.getMeta(wandNode, "active_spell", activeSpell); activeMaterial = InventoryUtils.getMeta(wandNode, "active_material", activeMaterial); costReduction = Float.parseFloat(InventoryUtils.getMeta(wandNode, "cost_reduction", floatFormat.format(costReduction))); cooldownReduction = Float.parseFloat(InventoryUtils.getMeta(wandNode, "cooldown_reduction", floatFormat.format(cooldownReduction))); power = Float.parseFloat(InventoryUtils.getMeta(wandNode, "power", floatFormat.format(power))); damageReduction = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection", floatFormat.format(damageReduction))); damageReductionPhysical = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_physical", floatFormat.format(damageReductionPhysical))); damageReductionProjectiles = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_projectiles", floatFormat.format(damageReductionProjectiles))); damageReductionFalling = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_falling", floatFormat.format(damageReductionFalling))); damageReductionFire = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_fire", floatFormat.format(damageReductionFire))); damageReductionExplosions = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_explosions", floatFormat.format(damageReductionExplosions))); speedIncrease = Float.parseFloat(InventoryUtils.getMeta(wandNode, "haste", floatFormat.format(speedIncrease))); xp = Integer.parseInt(InventoryUtils.getMeta(wandNode, "xp", Integer.toString(xp))); xpRegeneration = Integer.parseInt(InventoryUtils.getMeta(wandNode, "xp_regeneration", Integer.toString(xpRegeneration))); xpMax = Integer.parseInt(InventoryUtils.getMeta(wandNode, "xp_max", Integer.toString(xpMax))); healthRegeneration = Integer.parseInt(InventoryUtils.getMeta(wandNode, "health_regeneration", Integer.toString(healthRegeneration))); hungerRegeneration = Integer.parseInt(InventoryUtils.getMeta(wandNode, "hunger_regeneration", Integer.toString(hungerRegeneration))); uses = Integer.parseInt(InventoryUtils.getMeta(wandNode, "uses", Integer.toString(uses))); hasInventory = Integer.parseInt(InventoryUtils.getMeta(wandNode, "has_inventory", (hasInventory ? "1" : "0"))) != 0; modifiable = Integer.parseInt(InventoryUtils.getMeta(wandNode, "modifiable", (modifiable ? "1" : "0"))) != 0; effectColor = Integer.parseInt(InventoryUtils.getMeta(wandNode, "effect_color", Integer.toString(effectColor, 16)), 16); // This is done here as an extra safety measure. // A walk speed too high will cause a server error. speedIncrease = Math.min(WandLevel.maxSpeedIncrease, speedIncrease); } protected void describe(CommandSender sender) { Object wandNode = InventoryUtils.getNode(item, "wand"); if (wandNode == null) { sender.sendMessage("Found a wand with missing NBT data. This may be an old wand, or something may have wiped its data"); return; } ChatColor wandColor = modifiable ? ChatColor.AQUA : ChatColor.RED; sender.sendMessage(wandColor + wandName); if (description.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + description); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + "(No Description)"); } if (owner.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + owner); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + "(No Owner)"); } String[] keys = {"active_spell", "active_material", "xp", "xp_regeneration", "xp_max", "health_regeneration", "hunger_regeneration", "uses", "cost_reduction", "cooldown_reduction", "power", "protection", "protection_physical", "protection_projectiles", "protection_falling", "protection_fire", "protection_explosions", "haste", "has_inventory", "modifiable", "effect_color", "materials", "spells"}; for (String key : keys) { String value = InventoryUtils.getMeta(wandNode, key); if (value != null && value.length() > 0) { sender.sendMessage(key + ": " + value); } } } @SuppressWarnings("deprecation") public boolean removeMaterial(Material material, byte data) { if (!modifiable) return false; if (isInventoryOpen()) { saveInventory(); } Integer id = material.getId(); String materialString = id.toString(); materialString += ":" + data; if (materialString.equals(activeMaterial)) { activeMaterial = null; } List<Inventory> allInventories = getAllInventories(); boolean found = false; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (itemStack != null && itemStack.getType() != Material.AIR && !isWand(itemStack) && !isSpell(itemStack)) { if (itemStack.getType() == material && data == itemStack.getData().getData()) { found = true; inventory.setItem(index, null); } else if (activeMaterial == null) { activeMaterial = "" + itemStack.getTypeId() + ":" + (itemStack.getData().getData()); } if (found && activeMaterial != null) { break; } } } } updateActiveMaterial(); updateInventoryNames(true); updateName(); updateLore(); saveState(); if (isInventoryOpen()) { updateInventory(); } return found; } public boolean addMaterial(Material material, byte data, boolean force) { return addMaterial(material, data, false, force); } public boolean addMaterial(Material material, byte data) { return addMaterial(material, data, false, false); } public boolean hasMaterial(int materialId, byte data) { String materialName = materialId + ":" + data; return getMaterialNames().contains(materialName); } @SuppressWarnings("deprecation") public boolean hasMaterial(Material material, byte data) { return hasMaterial(material.getId(), data); } public boolean hasSpell(String spellName) { return getSpells().contains(spellName); } public boolean addMaterial(String materialName, boolean makeActive, boolean force) { if (!modifiable && !force) return false; Integer materialId = null; byte data = 0; try { String[] pieces = materialName.split(":"); data = pieces.length > 1 ? Byte.parseByte(pieces[1]) : 0; materialId =Integer.parseInt(pieces[0]); } catch (Exception ex) { materialId = null; } if (materialId == null) { return false; } boolean addedNew = !hasMaterial(materialId, data); if (addedNew) { addToInventory(createMaterialItem(materialId, data)); } if (activeMaterial == null || activeMaterial.length() == 0 || makeActive) { activeMaterial = materialName; } updateActiveMaterial(); updateInventoryNames(true); updateName(); updateLore(); saveState(); if (isInventoryOpen()) { updateInventory(); } hasInventory = getSpells().size() + getMaterialNames().size() > 1; return addedNew; } @SuppressWarnings("deprecation") public boolean addMaterial(Material material, byte data, boolean makeActive, boolean force) { if (!modifiable && !force) return false; if (isInventoryOpen()) { saveInventory(); } Integer id = material.getId(); String materialString = id.toString(); if (material == EraseMaterial) { materialString = "0"; } else if (material == CopyMaterial) { materialString = "-1"; } materialString += ":" + data; return addMaterial(materialString, makeActive, force); } public boolean removeSpell(String spellName) { if (!modifiable) return false; if (isInventoryOpen()) { saveInventory(); } if (spellName.equals(activeSpell)) { activeSpell = null; } List<Inventory> allInventories = getAllInventories(); boolean found = false; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (itemStack != null && itemStack.getType() != Material.AIR && !isWand(itemStack) && isSpell(itemStack)) { if (getSpell(itemStack).equals(spellName)) { found = true; inventory.setItem(index, null); } else if (activeSpell == null) { activeSpell = getSpell(itemStack); } if (found && activeSpell != null) { break; } } } } updateInventoryNames(true); updateName(); updateLore(); saveState(); if (isInventoryOpen()) { updateInventory(); } return found; } public boolean addSpell(String spellName, boolean makeActive) { if (!modifiable) return false; if (isInventoryOpen()) { saveInventory(); } boolean addedNew = !hasSpell(spellName); if (addedNew) { addToInventory(createSpellItem(spellName)); } if (activeSpell == null || activeSpell.length() == 0 || makeActive) { activeSpell = spellName; } hasInventory = getSpells().size() + getMaterialNames().size() > 1; updateInventoryNames(true); updateName(); updateLore(); saveState(); if (isInventoryOpen()) { updateInventory(); } return addedNew; } public boolean addSpell(String spellName) { return addSpell(spellName, false); } private String getActiveWandName(Spell spell, String materialName) { // Build wand name ChatColor wandColor = modifiable ? ChatColor.AQUA : ChatColor.RED; String name = wandColor + wandName; // Add active spell to description if (spell != null) { if (materialName != null) { materialName = materialName.replace('_', ' '); name = ChatColor.GOLD + spell.getName() + ChatColor.GRAY + " " + materialName + ChatColor.WHITE + " (" + wandColor + wandName + ChatColor.WHITE + ")"; } else { name = ChatColor.GOLD + spell.getName() + ChatColor.WHITE + " (" + wandColor + wandName + ChatColor.WHITE + ")"; } } int remaining = getRemainingUses(); if (remaining > 0) { name = name + " : " + ChatColor.RED + Messages.get("wand.uses_remaining_brief").replace("$count", ((Integer)remaining).toString()); } return name; } @SuppressWarnings("deprecation") private String getActiveWandName(Spell spell) { String[] pieces = StringUtils.split(activeMaterial, ":"); String materialName = null; if (spell != null && spell.usesMaterial() && !spell.hasMaterialOverride() && pieces.length > 0 && pieces[0].length() > 0) { int materialId = Integer.parseInt(pieces[0]); if (materialId == 0) { materialName = "erase"; } else if (materialId == -1) { materialName = "copy"; } else { Material material = Material.getMaterial(materialId); materialName = material.name().toLowerCase();; } } return getActiveWandName(spell, materialName); } private String getMaterialName(Material material) { return getMaterialName(material, (byte)0); } @SuppressWarnings("deprecation") private String getMaterialName(Material material, byte data) { String materialName = null; if (material == EraseMaterial) { materialName = "erase"; } else if (material == CopyMaterial) { materialName = "copy"; } else { materialName = material.name().toLowerCase(); // I started doing this the "right" way by looking at MaterialData // But I don't feel like waiting for Bukkit to update their classes. // This also seems super ugly and messy.. if this is the replacement for "magic numbers", count me out :P /* Class<? extends MaterialData> materialData = material.getData(); if (Dye.class.isAssignableFrom(materialData)) { Dye dye = new Dye(material, data); materialName += " " + dye.getColor().name(); } else if (Dye.class.isAssignableFrom(materialData)) { Dye dye = new Dye(material, data); materialName += " " + dye.getColor().name(); } */ if (material == Material.CARPET || material == Material.STAINED_GLASS || material == Material.STAINED_CLAY || material == Material.STAINED_GLASS_PANE || material == Material.WOOL) { // Note that getByDyeData doesn't work for stained glass or clay. Kind of misleading? DyeColor color = DyeColor.getByWoolData(data); materialName = color.name().toLowerCase().replace('_', ' ') + " " + materialName; } else if (material == Material.WOOD || material == Material.LOG || material == Material.SAPLING || material == Material.LEAVES) { TreeSpecies treeSpecies = TreeSpecies.getByData(data); materialName = treeSpecies.name().toLowerCase().replace('_', ' ') + " " + materialName; } } materialName = materialName.replace('_', ' '); return materialName; } private String getActiveWandName(Material material) { Spell spell = spells.getSpell(activeSpell); String materialName = null; if (spell != null && spell.usesMaterial() && !spell.hasMaterialOverride() && material != null) { materialName = getMaterialName(material); } return getActiveWandName(spell, materialName); } private String getActiveWandName() { Spell spell = null; if (hasInventory) { spell = spells.getSpell(activeSpell); } return getActiveWandName(spell); } public void updateName(boolean isActive) { ItemMeta meta = item.getItemMeta(); meta.setDisplayName(isActive ? getActiveWandName() : wandName); item.setItemMeta(meta); // Reset Enchantment glow InventoryUtils.addGlow(item); // The all-important last step of restoring the meta state, something // the Anvil will blow away. saveState(); } private void updateName() { updateName(true); } private String getLevelString(String prefix, float amount) { String suffix = ""; if (amount >= 1) { suffix = Messages.get("wand.enchantment_level_max"); } else if (amount > 0.8) { suffix = Messages.get("wand.enchantment_level_5"); } else if (amount > 0.6) { suffix = Messages.get("wand.enchantment_level_4"); } else if (amount > 0.4) { suffix = Messages.get("wand.enchantment_level_3"); } else if (amount > 0.2) { suffix = Messages.get("wand.enchantment_level_2"); } else { suffix = Messages.get("wand.enchantment_level_1"); } return prefix + " " + suffix; } protected static String convertToHTML(String line) { int tagCount = 1; line = "<span style=\"color:white\">" + line; for (ChatColor c : ChatColor.values()) { tagCount += StringUtils.countMatches(line, c.toString()); String replaceStyle = ""; if (c == ChatColor.ITALIC) { replaceStyle = "font-style: italic"; } else if (c == ChatColor.BOLD) { replaceStyle = "font-weight: bold"; } else if (c == ChatColor.UNDERLINE) { replaceStyle = "text-decoration: underline"; } else { String color = c.name().toLowerCase().replace("_", ""); if (c == ChatColor.LIGHT_PURPLE) { color = "mediumpurple"; } replaceStyle = "color:" + color; } line = line.replace(c.toString(), "<span style=\"" + replaceStyle + "\">"); } for (int i = 0; i < tagCount; i++) { line += "</span>"; } return line; } public String getHTMLDescription() { Collection<String> rawLore = getLore(); Collection<String> lore = new ArrayList<String>(); lore.add("<h2>" + convertToHTML(getActiveWandName()) + "</h2>"); for (String line : rawLore) { lore.add(convertToHTML(line)); } return "<div style=\"background-color: black; margin: 8px; padding: 8px\">" + StringUtils.join(lore, "<br/>") + "</div>"; } private List<String> getLore() { return getLore(getSpells().size(), getMaterialNames().size()); } private List<String> getLore(int spellCount, int materialCount) { List<String> lore = new ArrayList<String>(); Spell spell = spells.getSpell(activeSpell); if (spell != null && spellCount == 1 && materialCount <= 1) { addSpellLore(spell, lore); } else { if (description.length() > 0) { lore.add(ChatColor.ITALIC + "" + ChatColor.GREEN + description); } lore.add(Messages.get("wand.spell_count").replace("$count", ((Integer)spellCount).toString())); if (materialCount > 0) { lore.add(Messages.get("wand.material_count").replace("$count", ((Integer)materialCount).toString())); } } int remaining = getRemainingUses(); if (remaining > 0) { lore.add(ChatColor.RED + Messages.get("wand.uses_remaining").replace("$count", ((Integer)remaining).toString())); } if (xpRegeneration > 0) { lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + Messages.get("wand.mana_amount").replace("$amount", ((Integer)xpMax).toString())); lore.add(ChatColor.RESET + "" + ChatColor.LIGHT_PURPLE + getLevelString(Messages.get("wand.mana_regeneration"), xpRegeneration / WandLevel.maxXpRegeneration)); } if (costReduction > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.cost_reduction"), costReduction)); if (cooldownReduction > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.cooldown_reduction"), cooldownReduction)); if (power > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.power"), power)); if (speedIncrease > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.haste"), speedIncrease / WandLevel.maxSpeedIncrease)); if (damageReduction > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection"), damageReduction)); if (damageReduction < 1) { if (damageReductionPhysical > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_physical"), damageReductionPhysical)); if (damageReductionProjectiles > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_projectile"), damageReductionProjectiles)); if (damageReductionFalling > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_fall"), damageReductionFalling)); if (damageReductionFire > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_fire"), damageReductionFire)); if (damageReductionExplosions > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_blast"), damageReductionExplosions)); } if (healthRegeneration > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.health_regeneration"), healthRegeneration / WandLevel.maxRegeneration)); if (hungerRegeneration > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.hunger_regeneration"), hungerRegeneration / WandLevel.maxRegeneration)); return lore; } private void updateLore() { ItemMeta meta = item.getItemMeta(); List<String> lore = getLore(); meta.setLore(lore); item.setItemMeta(meta); InventoryUtils.addGlow(item); // Reset spell list and wand config saveState(); } public int getRemainingUses() { return uses; } public void makeEnchantable(boolean enchantable) { item.setType(enchantable ? EnchantableWandMaterial : WandMaterial); updateName(); } public static boolean hasActiveWand(Player player) { ItemStack activeItem = player.getInventory().getItemInHand(); return isWand(activeItem); } public static Wand getActiveWand(Spells spells, Player player) { ItemStack activeItem = player.getInventory().getItemInHand(); if (isWand(activeItem)) { return new Wand(spells, activeItem); } return null; } public static boolean isWand(ItemStack item) { // Special-case here for porting old wands. Could be removed eventually. return item != null && (item.getType() == WandMaterial || item.getType() == EnchantableWandMaterial) && (InventoryUtils.hasMeta(item, "wand") || InventoryUtils.hasMeta(item, "magic_wand")); } public static boolean isSpell(ItemStack item) { return item != null && item.getType() != WandMaterial && InventoryUtils.hasMeta(item, "spell"); } public static String getSpell(ItemStack item) { if (!isSpell(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); return InventoryUtils.getMeta(spellNode, "key"); } public void updateInventoryNames(boolean activeNames) { if (activePlayer == null || !isInventoryOpen()) return; ItemStack[] contents = activePlayer.getPlayer().getInventory().getContents(); for (ItemStack item : contents) { if (item == null || item.getType() == Material.AIR || isWand(item)) continue; updateInventoryName(item, activeNames); } } protected void updateInventoryName(ItemStack item, boolean activeName) { if (isSpell(item)) { Spell spell = activePlayer.getSpell(getSpell(item)); if (spell != null) { updateSpellName(item, spell, activeName); } } else { updateMaterialName(item, activeName); } } protected void updateSpellName(ItemStack itemStack, Spell spell, boolean activeName) { ItemMeta meta = itemStack.getItemMeta(); if (activeName) { meta.setDisplayName(getActiveWandName(spell)); } else { meta.setDisplayName(ChatColor.GOLD + spell.getName()); } List<String> lore = new ArrayList<String>(); addSpellLore(spell, lore); meta.setLore(lore); itemStack.setItemMeta(meta); InventoryUtils.addGlow(itemStack); Object spellNode = InventoryUtils.createNode(itemStack, "spell"); InventoryUtils.setMeta(spellNode, "key", spell.getKey()); } protected void updateMaterialName(ItemStack itemStack, boolean activeName) { ItemMeta meta = itemStack.getItemMeta(); if (activeName) { meta.setDisplayName(getActiveWandName(itemStack.getType())); } else { meta.setDisplayName(getMaterialName(itemStack.getType())); } itemStack.setItemMeta(meta); } @SuppressWarnings("deprecation") private void updateInventory() { if (activePlayer == null) return; if (!isInventoryOpen()) return; if (activePlayer.getPlayer() == null) return; if (!activePlayer.hasStoredInventory()) return; // Clear the player's inventory Player player = activePlayer.getPlayer(); PlayerInventory playerInventory = player.getInventory(); playerInventory.clear(); // First add the wand and check the hotbar for conflicts int currentSlot = playerInventory.getHeldItemSlot(); ItemStack existingHotbar = hotbar.getItem(currentSlot); if (existingHotbar != null && existingHotbar.getType() != Material.AIR && !isWand(existingHotbar)) { addToInventory(existingHotbar); hotbar.setItem(currentSlot, null); } playerInventory.setItem(currentSlot, item); // Set hotbar for (int hotbarSlot = 0; hotbarSlot < hotbarSize; hotbarSlot++) { if (hotbarSlot != currentSlot) { playerInventory.setItem(hotbarSlot, hotbar.getItem(hotbarSlot)); } } // Set inventory from current page if (openInventoryPage < inventories.size()) { Inventory inventory = inventories.get(openInventoryPage); ItemStack[] contents = inventory.getContents(); for (int i = 0; i < contents.length; i++) { playerInventory.setItem(i + hotbarSize, contents[i]); } } updateName(); player.updateInventory(); } protected void addSpellLore(Spell spell, List<String> lore) { String description = spell.getDescription(); String usage = spell.getUsage(); if (description != null && description.length() > 0) { lore.add(description); } if (usage != null && usage.length() > 0) { lore.add(usage); } List<CastingCost> costs = spell.getCosts(); if (costs != null) { for (CastingCost cost : costs) { if (cost.hasCosts(this)) { lore.add(ChatColor.YELLOW + Messages.get("wand.costs_description").replace("$description", cost.getFullDescription(this))); } } } } protected Inventory getOpenInventory() { while (openInventoryPage >= inventories.size()) { inventories.add(InventoryUtils.createInventory(null, inventorySize, "Wand")); } return inventories.get(openInventoryPage); } public void saveInventory() { if (activePlayer == null) return; if (activePlayer == null) return; if (!isInventoryOpen()) return; if (activePlayer.getPlayer() == null) return; if (!activePlayer.hasStoredInventory()) return; // Fill in the hotbar Player player = activePlayer.getPlayer(); PlayerInventory playerInventory = player.getInventory(); for (int i = 0; i < hotbarSize; i++) { ItemStack playerItem = playerInventory.getItem(i); if (isWand(playerItem)) { playerItem = null; } hotbar.setItem(i, playerItem); } // Fill in the active inventory page Inventory openInventory = getOpenInventory(); for (int i = 0; i < openInventory.getSize(); i++) { openInventory.setItem(i, playerInventory.getItem(i + hotbarSize)); } saveState(); } public static boolean isActive(Player player) { ItemStack activeItem = player.getInventory().getItemInHand(); return isWand(activeItem); } protected void randomize(int level, boolean additive) { if (!wandTemplates.containsKey("random")) return; if (!additive) { wandName = Messages.get("wands.random.name", wandName); } WandLevel.randomizeWand(this, additive, level); } public static Wand createWand(Spells spells, String templateName) { Wand wand = new Wand(spells); String wandName = Messages.get("wand.default_name"); String wandDescription = ""; // Check for default wand if ((templateName == null || templateName.length() == 0) && wandTemplates.containsKey("default")) { templateName = "default"; } // See if there is a template with this key if (templateName != null && templateName.length() > 0) { if ((templateName.equals("random") || templateName.startsWith("random(")) && wandTemplates.containsKey("random")) { int level = 1; if (!templateName.equals("random")) { String randomLevel = templateName.substring(templateName.indexOf('(') + 1, templateName.length() - 1); level = Integer.parseInt(randomLevel); } ConfigurationNode randomTemplate = wandTemplates.get("random"); wand.modifiable = (boolean)randomTemplate.getBoolean("modifiable", true); wand.randomize(level, false); return wand; } if (!wandTemplates.containsKey(templateName)) { return null; } ConfigurationNode wandConfig = wandTemplates.get(templateName); wandName = Messages.get("wands." + templateName + ".name", wandName); wandDescription = Messages.get("wands." + templateName + ".description", wandDescription); List<Object> spellList = wandConfig.getList("spells"); if (spellList != null) { for (Object spellName : spellList) { wand.addSpell((String)spellName); } } List<Object> materialList = wandConfig.getList("materials"); if (materialList != null) { for (Object materialNameAndData : materialList) { String[] materialParts = StringUtils.split((String)materialNameAndData, ':'); String materialName = materialParts[0]; byte data = 0; if (materialParts.length > 1) { data = Byte.parseByte(materialParts[1]); } if (materialName.equals("erase")) { wand.addMaterial(EraseMaterial, (byte)0, false); } else if (materialName.equals("copy") || materialName.equals("clone")) { wand.addMaterial(CopyMaterial, (byte)0, false); } else { wand.addMaterial(ConfigurationNode.toMaterial(materialName), data, false); } } } wand.configureProperties(wandConfig); } wand.setDescription(wandDescription); wand.setName(wandName); return wand; } public void add(Wand other) { if (!modifiable || !other.modifiable) return; costReduction = Math.max(costReduction, other.costReduction); power = Math.max(power, other.power); damageReduction = Math.max(damageReduction, other.damageReduction); damageReductionPhysical = Math.max(damageReductionPhysical, other.damageReductionPhysical); damageReductionProjectiles = Math.max(damageReductionProjectiles, other.damageReductionProjectiles); damageReductionFalling = Math.max(damageReductionFalling, other.damageReductionFalling); damageReductionFire = Math.max(damageReductionFire, other.damageReductionFire); damageReductionExplosions = Math.max(damageReductionExplosions, other.damageReductionExplosions); xpRegeneration = Math.max(xpRegeneration, other.xpRegeneration); xpMax = Math.max(xpMax, other.xpMax); xp = Math.max(xp, other.xp); healthRegeneration = Math.max(healthRegeneration, other.healthRegeneration); hungerRegeneration = Math.max(hungerRegeneration, other.hungerRegeneration); speedIncrease = Math.max(speedIncrease, other.speedIncrease); effectColor = Math.max(effectColor, other.effectColor); // Eliminate limited-use wands if (uses == 0 || other.uses == 0) { uses = 0; } else { // Otherwise add them uses = uses + other.uses; } // Add spells Set<String> spells = other.getSpells(); for (String spell : spells) { addSpell(spell, false); } // Add materials Set<String> materials = other.getMaterialNames(); for (String material : materials) { addMaterial(material, false, true); } saveState(); updateName(); updateLore(); } public void configureProperties(ConfigurationNode wandConfig) { configureProperties(wandConfig, false); } public void configureProperties(ConfigurationNode wandConfig, boolean safe) { modifiable = (boolean)wandConfig.getBoolean("modifiable", modifiable); float _costReduction = (float)wandConfig.getDouble("cost_reduction", costReduction); costReduction = safe ? Math.max(_costReduction, costReduction) : _costReduction; float _cooldownReduction = (float)wandConfig.getDouble("cooldown_reduction", cooldownReduction); cooldownReduction = safe ? Math.max(_cooldownReduction, cooldownReduction) : _cooldownReduction; float _power = (float)wandConfig.getDouble("power", power); power = safe ? Math.max(_power, power) : _power; float _damageReduction = (float)wandConfig.getDouble("protection", damageReduction); damageReduction = safe ? Math.max(_damageReduction, damageReduction) : _damageReduction; float _damageReductionPhysical = (float)wandConfig.getDouble("protection_physical", damageReductionPhysical); damageReductionPhysical = safe ? Math.max(_damageReductionPhysical, damageReductionPhysical) : _damageReductionPhysical; float _damageReductionProjectiles = (float)wandConfig.getDouble("protection_projectiles", damageReductionProjectiles); damageReductionProjectiles = safe ? Math.max(_damageReductionProjectiles, damageReductionPhysical) : _damageReductionProjectiles; float _damageReductionFalling = (float)wandConfig.getDouble("protection_falling", damageReductionFalling); damageReductionFalling = safe ? Math.max(_damageReductionFalling, damageReductionFalling) : _damageReductionFalling; float _damageReductionFire = (float)wandConfig.getDouble("protection_fire", damageReductionFire); damageReductionFire = safe ? Math.max(_damageReductionFire, damageReductionFire) : _damageReductionFire; float _damageReductionExplosions = (float)wandConfig.getDouble("protection_explosions", damageReductionExplosions); damageReductionExplosions = safe ? Math.max(_damageReductionExplosions, damageReductionExplosions) : _damageReductionExplosions; int _xpRegeneration = wandConfig.getInt("xp_regeneration", xpRegeneration); xpRegeneration = safe ? Math.max(_xpRegeneration, xpRegeneration) : _xpRegeneration; int _xpMax = wandConfig.getInt("xp_max", xpMax); xpMax = safe ? Math.max(_xpMax, xpMax) : _xpMax; int _xp = wandConfig.getInt("xp", xp); xp = safe ? Math.max(_xp, xp) : _xp; int _healthRegeneration = wandConfig.getInt("health_regeneration", healthRegeneration); healthRegeneration = safe ? Math.max(_healthRegeneration, healthRegeneration) : _healthRegeneration; int _hungerRegeneration = wandConfig.getInt("hunger_regeneration", hungerRegeneration); hungerRegeneration = safe ? Math.max(_hungerRegeneration, hungerRegeneration) : _hungerRegeneration; int _uses = wandConfig.getInt("uses", uses); uses = safe ? Math.max(_uses, uses) : _uses; effectColor = Integer.parseInt(wandConfig.getString("effect_color", "0"), 16); // Make sure to adjust the player's walk speed if it changes and this wand is active. float oldWalkSpeedIncrease = speedIncrease; speedIncrease = (float)wandConfig.getDouble("haste", speedIncrease); if (activePlayer != null && speedIncrease != oldWalkSpeedIncrease) { Player player = activePlayer.getPlayer(); player.setWalkSpeed(defaultWalkSpeed + speedIncrease); player.setFlySpeed(defaultFlySpeed + speedIncrease); } saveState(); updateName(); updateLore(); } public static void reset(Plugin plugin) { File dataFolder = plugin.getDataFolder(); File propertiesFile = new File(dataFolder, propertiesFileName); propertiesFile.delete(); } public static void load(Plugin plugin) { // Load properties file with wand templates File dataFolder = plugin.getDataFolder(); File oldDefaults = new File(dataFolder, propertiesFileNameDefaults); oldDefaults.delete(); plugin.getLogger().info("Overwriting file " + propertiesFileNameDefaults); plugin.saveResource(propertiesFileNameDefaults, false); File propertiesFile = new File(dataFolder, propertiesFileName); if (!propertiesFile.exists()) { plugin.getLogger().info("Loading default wands from " + propertiesFileNameDefaults); loadProperties(plugin.getResource(propertiesFileNameDefaults)); } else { plugin.getLogger().info("Loading wands from " + propertiesFile.getName()); loadProperties(propertiesFile); } } private static void loadProperties(File propertiesFile) { loadProperties(new Configuration(propertiesFile)); } private static void loadProperties(InputStream properties) { loadProperties(new Configuration(properties)); } private static void loadProperties(Configuration properties) { properties.load(); wandTemplates.clear(); ConfigurationNode wandList = properties.getNode("wands"); if (wandList == null) return; List<String> wandKeys = wandList.getKeys(); for (String key : wandKeys) { ConfigurationNode wandNode = wandList.getNode(key); wandNode.setProperty("key", key); wandTemplates.put(key, wandNode); if (key.equals("random")) { WandLevel.mapLevels(wandNode); } } } public static Collection<ConfigurationNode> getWandTemplates() { return wandTemplates.values(); } @SuppressWarnings("deprecation") private void updateActiveMaterial() { if (activePlayer == null) return; if (activeMaterial == null) { activePlayer.clearBuildingMaterial(); } else { String[] pieces = StringUtils.split(activeMaterial, ":"); if (pieces.length > 0) { byte data = 0; if (pieces.length > 1) { data = Byte.parseByte(pieces[1]); } int materialId = Integer.parseInt(pieces[0]); Material material = null; if (materialId == 0) { material = EraseMaterial; } else if (materialId == -1) { material = CopyMaterial; } else { material = Material.getMaterial(materialId); } activePlayer.setBuildingMaterial(material, data); } } } public void toggleInventory() { if (!hasInventory) { return; } if (!isInventoryOpen()) { openInventory(); } else { closeInventory(); } } @SuppressWarnings("deprecation") public void cycleInventory() { if (!hasInventory) { return; } if (isInventoryOpen()) { saveInventory(); openInventoryPage = (openInventoryPage + 1) % inventories.size(); updateInventory(); if (activePlayer != null && inventories.size() > 1) { activePlayer.playSound(Sound.CHEST_OPEN, 0.3f, 1.5f); activePlayer.getPlayer().updateInventory(); } } } @SuppressWarnings("deprecation") private void openInventory() { if (activePlayer == null) return; if (activePlayer.hasStoredInventory()) return; if (activePlayer.storeInventory()) { inventoryIsOpen = true; activePlayer.playSound(Sound.CHEST_OPEN, 0.4f, 0.2f); updateInventory(); activePlayer.getPlayer().updateInventory(); } } @SuppressWarnings("deprecation") public void closeInventory() { if (!isInventoryOpen()) return; saveInventory(); inventoryIsOpen = false; if (activePlayer != null) { activePlayer.playSound(Sound.CHEST_CLOSE, 0.4f, 0.2f); activePlayer.restoreInventory(); activePlayer.getPlayer().updateInventory(); ItemStack newWandItem = activePlayer.getPlayer().getInventory().getItemInHand(); if (isWand(newWandItem)) { item = newWandItem; updateName(); } } saveState(); } public void activate(PlayerSpells playerSpells) { if (owner.length() == 0) { takeOwnership(playerSpells.getPlayer()); } activePlayer = playerSpells; Player player = activePlayer.getPlayer(); if (speedIncrease > 0) { try { player.setWalkSpeed(defaultWalkSpeed + speedIncrease); player.setFlySpeed(defaultFlySpeed + speedIncrease); } catch(Exception ex2) { try { player.setWalkSpeed(defaultWalkSpeed); player.setFlySpeed(defaultFlySpeed); } catch(Exception ex) { } } } activePlayer.setActiveWand(this); if (xpRegeneration > 0) { storedXpLevel = player.getLevel(); storedXpProgress = player.getExp(); storedXp = 0; updateMana(); } updateActiveMaterial(); updateName(); if (effectColor != 0) { InventoryUtils.addPotionEffect(player, effectColor); } } protected void updateMana() { if (activePlayer != null && xpMax > 0 && xpRegeneration > 0) { Player player = activePlayer.getPlayer(); player.setLevel(0); player.setExp((float)xp / (float)xpMax); } } public boolean isInventoryOpen() { return activePlayer != null && inventoryIsOpen; } public void deactivate() { if (activePlayer == null) return; saveState(); if (effectColor > 0) { InventoryUtils.removePotionEffect(activePlayer.getPlayer()); } // This is a tying wands together with other spells, potentially // But with the way the mana system works, this seems like the safest route. activePlayer.deactivateAllSpells(); if (isInventoryOpen()) { closeInventory(); } // Extra just-in-case activePlayer.restoreInventory(); if (xpRegeneration > 0) { activePlayer.player.setExp(storedXpProgress); activePlayer.player.setLevel(storedXpLevel); activePlayer.player.giveExp(storedXp); storedXp = 0; storedXpProgress = 0; storedXpLevel = 0; } if (speedIncrease > 0) { try { activePlayer.getPlayer().setWalkSpeed(defaultWalkSpeed); activePlayer.getPlayer().setFlySpeed(defaultFlySpeed); } catch(Exception ex) { } } activePlayer.setActiveWand(null); activePlayer = null; } public Spell getActiveSpell() { if (activePlayer == null) return null; return activePlayer.getSpell(activeSpell); } public boolean cast() { Spell spell = getActiveSpell(); if (spell != null) { if (spell.cast()) { use(); return true; } } return false; } @SuppressWarnings("deprecation") protected void use() { if (activePlayer == null) return; if (uses > 0) { uses--; if (uses <= 0) { Player player = activePlayer.getPlayer(); activePlayer.playSound(Sound.ITEM_BREAK, 1.0f, 0.8f); PlayerInventory playerInventory = player.getInventory(); playerInventory.setItemInHand(new ItemStack(Material.AIR, 1)); player.updateInventory(); deactivate(); } else { updateName(); updateLore(); saveState(); } } } public void onPlayerExpChange(PlayerExpChangeEvent event) { if (activePlayer == null) return; if (xpRegeneration > 0) { storedXp += event.getAmount(); event.setAmount(0); } } public void processRegeneration() { if (activePlayer == null) return; Player player = activePlayer.getPlayer(); if (xpRegeneration > 0) { xp = Math.min(xpMax, xp + xpRegeneration); updateMana(); } double maxHealth = player.getMaxHealth(); if (healthRegeneration > 0 && player.getHealth() < maxHealth) { player.setHealth(Math.min(maxHealth, player.getHealth() + healthRegeneration)); } double maxFoodLevel = 20; if (hungerRegeneration > 0 && player.getFoodLevel() < maxFoodLevel) { player.setExhaustion(0); player.setFoodLevel(Math.min(20, player.getFoodLevel() + hungerRegeneration)); } if (damageReductionFire > 0 && player.getFireTicks() > 0) { player.setFireTicks(0); } } @Override public boolean equals(Object other) { if (other == null) return false; if (!(other instanceof Wand)) return false; Wand otherWand = ((Wand)other); if (this.id == null || otherWand.id == null) return false; return otherWand.id.equals(this.id); } public Spells getMaster() { return spells; } public void cycleSpells() { Set<String> spellsSet = getSpells(); String[] spells = (String[])spellsSet.toArray(); if (spells.length == 0) return; if (activeSpell == null) { activeSpell = spells[0].split("@")[0]; return; } int spellIndex = 0; for (int i = 0; i < spells.length; i++) { if (spells[i].split("@")[0].equals(activeSpell)) { spellIndex = i; break; } } spellIndex = (spellIndex + 1) % spells.length; setActiveSpell(spells[spellIndex].split("@")[0]); } public void cycleMaterials() { Set<String> materialsSet = getMaterialNames(); String[] materials = (String[])materialsSet.toArray(); if (materials.length == 0) return; if (activeMaterial == null) { activeMaterial = materials[0].split("@")[0]; return; } int materialIndex = 0; for (int i = 0; i < materials.length; i++) { if (materials[i].split("@")[0].equals(activeMaterial)) { materialIndex = i; break; } } materialIndex = (materialIndex + 1) % materials.length; setActiveMaterial(materials[materialIndex].split("@")[0]); } public boolean hasExperience() { return xpRegeneration > 0; } public void organizeInventory() { if (activePlayer == null) return; if (!isInventoryOpen()) return; WandOrganizer organizer = new WandOrganizer(this); organizer.organize(); openInventoryPage = 0; updateInventory(); saveState(); } public PlayerSpells getActivePlayer() { return activePlayer; } public String getId() { return this.id; } protected void clearInventories() { inventories.clear(); } }
Mix wand colors when combining wands.
src/main/java/com/elmakers/mine/bukkit/plugins/magic/Wand.java
Mix wand colors when combining wands.
<ide><path>rc/main/java/com/elmakers/mine/bukkit/plugins/magic/Wand.java <ide> <ide> import org.apache.commons.lang.StringUtils; <ide> import org.bukkit.ChatColor; <add>import org.bukkit.Color; <ide> import org.bukkit.DyeColor; <ide> import org.bukkit.Material; <ide> import org.bukkit.Sound; <ide> healthRegeneration = Math.max(healthRegeneration, other.healthRegeneration); <ide> hungerRegeneration = Math.max(hungerRegeneration, other.hungerRegeneration); <ide> speedIncrease = Math.max(speedIncrease, other.speedIncrease); <add> // Mix colors? <add> if (effectColor == 0) { <add> effectColor = other.effectColor; <add> } else if (other.effectColor != 0){ <add> Color color1 = Color.fromBGR(effectColor); <add> Color color2 = Color.fromBGR(other.effectColor); <add> Color newColor = color1.mixColors(color2); <add> effectColor = newColor.asRGB(); <add> } <ide> effectColor = Math.max(effectColor, other.effectColor); <ide> <ide> // Eliminate limited-use wands
Java
mpl-2.0
341f5806c216e3a612163f3245beaa0b77e3f80e
0
fredoboulo/jeromq,fredoboulo/jeromq,trevorbernard/jeromq,c-rack/jeromq,zeromq/jeromq,trevorbernard/jeromq,zeromq/jeromq
/* Copyright (c) 1991-2011 iMatix Corporation <www.imatix.com> Copyright other contributors as noted in the AUTHORS file. This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.zeromq; import java.nio.ByteBuffer; import java.nio.channels.SelectableChannel; import zmq.Ctx; import zmq.DecoderBase; import zmq.EncoderBase; import zmq.SocketBase; import zmq.ZError; public class ZMQ { /** * Socket flag to indicate that more message parts are coming. */ public static final int SNDMORE = zmq.ZMQ.ZMQ_SNDMORE; // Values for flags in Socket's send and recv functions. /** * Socket flag to indicate a nonblocking send or recv mode. */ public static final int DONTWAIT = zmq.ZMQ.ZMQ_DONTWAIT; public static final int NOBLOCK = zmq.ZMQ.ZMQ_DONTWAIT; // Socket types, used when creating a Socket. /** * Flag to specify a exclusive pair of sockets. */ public static final int PAIR = zmq.ZMQ.ZMQ_PAIR; /** * Flag to specify a PUB socket, receiving side must be a SUB or XSUB. */ public static final int PUB = zmq.ZMQ.ZMQ_PUB; /** * Flag to specify the receiving part of the PUB or XPUB socket. */ public static final int SUB = zmq.ZMQ.ZMQ_SUB; /** * Flag to specify a REQ socket, receiving side must be a REP. */ public static final int REQ = zmq.ZMQ.ZMQ_REQ; /** * Flag to specify the receiving part of a REQ socket. */ public static final int REP = zmq.ZMQ.ZMQ_REP; /** * Flag to specify a DEALER socket (aka XREQ). * DEALER is really a combined ventilator / sink * that does load-balancing on output and fair-queuing on input * with no other semantics. It is the only socket type that lets * you shuffle messages out to N nodes and shuffle the replies * back, in a raw bidirectional asynch pattern. */ public static final int DEALER = zmq.ZMQ.ZMQ_DEALER; /** * Old alias for DEALER flag. * Flag to specify a XREQ socket, receiving side must be a XREP. * * @deprecated As of release 3.0 of zeromq, replaced by {@link #DEALER} */ public static final int XREQ = DEALER; /** * Flag to specify ROUTER socket (aka XREP). * ROUTER is the socket that creates and consumes request-reply * routing envelopes. It is the only socket type that lets you route * messages to specific connections if you know their identities. */ public static final int ROUTER = zmq.ZMQ.ZMQ_ROUTER; /** * Old alias for ROUTER flag. * Flag to specify the receiving part of a XREQ socket. * * @deprecated As of release 3.0 of zeromq, replaced by {@link #ROUTER} */ public static final int XREP = ROUTER; /** * Flag to specify the receiving part of a PUSH socket. */ public static final int PULL = zmq.ZMQ.ZMQ_PULL; /** * Flag to specify a PUSH socket, receiving side must be a PULL. */ public static final int PUSH = zmq.ZMQ.ZMQ_PUSH; /** * Flag to specify a XPUB socket, receiving side must be a SUB or XSUB. * Subscriptions can be received as a message. Subscriptions start with * a '1' byte. Unsubscriptions start with a '0' byte. */ public static final int XPUB = zmq.ZMQ.ZMQ_XPUB; /** * Flag to specify the receiving part of the PUB or XPUB socket. Allows */ public static final int XSUB = zmq.ZMQ.ZMQ_XSUB; /** * Flag to specify a STREAMER device. */ public static final int STREAMER = zmq.ZMQ.ZMQ_STREAMER ; /** * Flag to specify a FORWARDER device. */ public static final int FORWARDER = zmq.ZMQ.ZMQ_FORWARDER ; /** * Flag to specify a QUEUE device. */ public static final int QUEUE = zmq.ZMQ.ZMQ_QUEUE ; /** * @see org.zeromq.ZMQ#PULL */ @Deprecated public static final int UPSTREAM = PULL; /** * @see org.zeromq.ZMQ#PUSH */ @Deprecated public static final int DOWNSTREAM = PUSH; /** * ZMQ Events */ public static final int EVENT_CONNECTED = zmq.ZMQ.ZMQ_EVENT_CONNECTED; public static final int EVENT_DELAYED = zmq.ZMQ.ZMQ_EVENT_CONNECT_DELAYED; public static final int EVENT_RETRIED = zmq.ZMQ.ZMQ_EVENT_CONNECT_RETRIED; public static final int EVENT_CONNECT_FAILED = zmq.ZMQ.ZMQ_EVENT_CONNECT_FAILED; public static final int EVENT_LISTENING = zmq.ZMQ.ZMQ_EVENT_LISTENING; public static final int EVENT_BIND_FAILED = zmq.ZMQ.ZMQ_EVENT_BIND_FAILED; public static final int EVENT_ACCEPTED = zmq.ZMQ.ZMQ_EVENT_ACCEPTED; public static final int EVENT_ACCEPT_FAILED = zmq.ZMQ.ZMQ_EVENT_ACCEPT_FAILED; public static final int EVENT_CLOSED = zmq.ZMQ.ZMQ_EVENT_CLOSED; public static final int EVENT_CLOSE_FAILED = zmq.ZMQ.ZMQ_EVENT_CLOSE_FAILED; public static final int EVENT_DISCONNECTED = zmq.ZMQ.ZMQ_EVENT_DISCONNECTED; public static final int EVENT_ALL = zmq.ZMQ.ZMQ_EVENT_ALL; /** * Create a new Context. * * @param ioThreads * Number of threads to use, usually 1 is sufficient for most use cases. * @return the Context */ public static Context context(int ioThreads) { return new Context(ioThreads); } public static class Context { private final Ctx ctx; /** * Class constructor. * * @param ioThreads * size of the threads pool to handle I/O operations. */ protected Context(int ioThreads) { ctx = zmq.ZMQ.zmq_init(ioThreads); } /** * This is an explicit "destructor". It can be called to ensure the corresponding 0MQ * Context has been disposed of. */ public void term() { ctx.terminate(); } /** * Create a new Socket within this context. * * @param type * the socket type. * @return the newly created Socket. */ public Socket socket(int type) { return new Socket(this, type); } /** * Create a new Poller within this context, with a default size. * * @return the newly created Poller. * @deprecated Use poller constructor */ public Poller poller () { return new Poller (this); } /** * Create a new Poller within this context, with a specified initial size. * * @param size * the poller initial size. * @return the newly created Poller. * @deprecated Use poller constructor */ public Poller poller (int size) { return new Poller (this, size); } } public static class Socket { // This port range is defined by IANA for dynamic or private ports // We use this when choosing a port for dynamic binding. private static final int DYNFROM = 0xc000; private static final int DYNTO = 0xffff; private final Ctx ctx; private final SocketBase base; /** * Class constructor. * * @param context * a 0MQ context previously created. * @param type * the socket type. */ protected Socket(Context context, int type) { ctx = context.ctx; base = ctx.create_socket(type); mayRaise(); } protected Socket(SocketBase base_) { ctx = null; base = base_; } /** * DO NOT USE if you're trying to build a special proxy * * @return raw zmq.SocketBase */ public SocketBase base() { return base; } private final static void mayRaise () { if (!ZError.is (0) && !ZError.is (ZError.EAGAIN)) throw new ZMQException (ZError.errno ()); } private final static void mayRaiseNot (int codeToIgnore) { if (!ZError.is (codeToIgnore)) mayRaise (); } /** * This is an explicit "destructor". It can be called to ensure the corresponding 0MQ Socket * has been disposed of. */ public final void close() { base.close(); } /** * The 'ZMQ_TYPE option shall retrieve the socket type for the specified * 'socket'. The socket type is specified at socket creation time and * cannot be modified afterwards. * * @return the socket type. */ public final int getType () { return base.getsockopt(zmq.ZMQ.ZMQ_TYPE); } /** * @see #setLinger(long) * * @return the linger period. */ public final long getLinger() { return base.getsockopt(zmq.ZMQ.ZMQ_LINGER); } /** * The 'ZMQ_LINGER' option shall retrieve the period for pending outbound * messages to linger in memory after closing the socket. Value of -1 means * infinite. Pending messages will be kept until they are fully transferred to * the peer. Value of 0 means that all the pending messages are dropped immediately * when socket is closed. Positive value means number of milliseconds to keep * trying to send the pending messages before discarding them. * * @param value * the linger period in milliseconds. */ public final void setLinger (long value) { base.setsockopt (zmq.ZMQ.ZMQ_LINGER, (int) value); mayRaiseNot (ZError.ETERM); } /** * @see #setReconnectIVL(long) * * @return the reconnectIVL. */ public final long getReconnectIVL() { return base.getsockopt(zmq.ZMQ.ZMQ_RECONNECT_IVL); } /** */ public final void setReconnectIVL(long value) { base.setsockopt(zmq.ZMQ.ZMQ_RECONNECT_IVL, (int)value); mayRaiseNot (ZError.ETERM); } /** * @see #setBacklog(long) * * @return the backlog. */ public final long getBacklog() { return base.getsockopt(zmq.ZMQ.ZMQ_BACKLOG); } /** */ public final void setBacklog(long value) { base.setsockopt(zmq.ZMQ.ZMQ_BACKLOG, (int)value); mayRaiseNot (ZError.ETERM); } /** * @see #setReconnectIVLMax(long) * * @return the reconnectIVLMax. */ public final long getReconnectIVLMax () { return base.getsockopt(zmq.ZMQ.ZMQ_RECONNECT_IVL_MAX); } /** */ public final void setReconnectIVLMax (long value) { base.setsockopt(zmq.ZMQ.ZMQ_RECONNECT_IVL_MAX, (int)value); mayRaiseNot (ZError.ETERM); } /** * @see #setMaxMsgSize(long) * * @return the maxMsgSize. */ public final long getMaxMsgSize() { return (Long)base.getsockoptx(zmq.ZMQ.ZMQ_MAXMSGSIZE); } /** */ public final void setMaxMsgSize(long value) { base.setsockopt(zmq.ZMQ.ZMQ_MAXMSGSIZE, value); mayRaiseNot (ZError.ETERM); } /** * @see #setSndHWM(long) * * @return the SndHWM. */ public final long getSndHWM() { return base.getsockopt(zmq.ZMQ.ZMQ_SNDHWM); } /** */ public final void setSndHWM(long value) { base.setsockopt(zmq.ZMQ.ZMQ_SNDHWM, (int)value); mayRaiseNot (ZError.ETERM); } /** * @see #setRcvHWM(long) * * @return the recvHWM period. */ public final long getRcvHWM() { return base.getsockopt(zmq.ZMQ.ZMQ_RCVHWM); } /** */ public final void setRcvHWM(long value) { base.setsockopt(zmq.ZMQ.ZMQ_RCVHWM, (int)value); mayRaiseNot (ZError.ETERM); } /** * @see #setHWM(long) * * @return the High Water Mark. */ @Deprecated public final long getHWM() { return -1; } /** * The 'ZMQ_HWM' option shall set the high water mark for the specified 'socket'. The high * water mark is a hard limit on the maximum number of outstanding messages 0MQ shall queue * in memory for any single peer that the specified 'socket' is communicating with. * * If this limit has been reached the socket shall enter an exceptional state and depending * on the socket type, 0MQ shall take appropriate action such as blocking or dropping sent * messages. Refer to the individual socket descriptions in the man page of zmq_socket[3] for * details on the exact action taken for each socket type. * * @param hwm * the number of messages to queue. */ public final void setHWM(long hwm) { setSndHWM (hwm); setRcvHWM (hwm); } /** * @see #setSwap(long) * * @return the number of messages to swap at most. */ @Deprecated public final long getSwap() { // not support at zeromq 3 return -1L; } /** * Get the Swap. The 'ZMQ_SWAP' option shall set the disk offload (swap) size for the * specified 'socket'. A socket which has 'ZMQ_SWAP' set to a non-zero value may exceed its * high water mark; in this case outstanding messages shall be offloaded to storage on disk * rather than held in memory. * * @param value * The value of 'ZMQ_SWAP' defines the maximum size of the swap space in bytes. */ @Deprecated public final void setSwap(long value) { throw new UnsupportedOperationException (); } /** * @see #setAffinity(long) * * @return the affinity. */ public final long getAffinity() { return (Long)base.getsockoptx(zmq.ZMQ.ZMQ_AFFINITY); } /** * Get the Affinity. The 'ZMQ_AFFINITY' option shall set the I/O thread affinity for newly * created connections on the specified 'socket'. * * Affinity determines which threads from the 0MQ I/O thread pool associated with the * socket's _context_ shall handle newly created connections. A value of zero specifies no * affinity, meaning that work shall be distributed fairly among all 0MQ I/O threads in the * thread pool. For non-zero values, the lowest bit corresponds to thread 1, second lowest * bit to thread 2 and so on. For example, a value of 3 specifies that subsequent * connections on 'socket' shall be handled exclusively by I/O threads 1 and 2. * * See also in the man page of zmq_init[3] for details on allocating the number of I/O threads for a * specific _context_. * * @param value * the io_thread affinity. */ public final void setAffinity (long value) { base.setsockopt(zmq.ZMQ.ZMQ_AFFINITY, value); mayRaiseNot (ZError.ETERM); } /** * @see #setIdentity(byte[]) * * @return the Identitiy. */ public final byte[] getIdentity() { return (byte[]) base.getsockoptx(zmq.ZMQ.ZMQ_IDENTITY); } /** * The 'ZMQ_IDENTITY' option shall set the identity of the specified 'socket'. Socket * identity determines if existing 0MQ infastructure (_message queues_, _forwarding * devices_) shall be identified with a specific application and persist across multiple * runs of the application. * * If the socket has no identity, each run of an application is completely separate from * other runs. However, with identity set the socket shall re-use any existing 0MQ * infrastructure configured by the previous run(s). Thus the application may receive * messages that were sent in the meantime, _message queue_ limits shall be shared with * previous run(s) and so on. * * Identity should be at least one byte and at most 255 bytes long. Identities starting with * binary zero are reserved for use by 0MQ infrastructure. * * @param identity */ public final void setIdentity(byte[] identity) { base.setsockopt(zmq.ZMQ.ZMQ_IDENTITY, identity); mayRaiseNot (ZError.ETERM); } /** * @see #setRate(long) * * @return the Rate. */ public final long getRate() { return base.getsockopt(zmq.ZMQ.ZMQ_RATE); } /** * The 'ZMQ_RATE' option shall set the maximum send or receive data rate for multicast * transports such as in the man page of zmq_pgm[7] using the specified 'socket'. * * @param value maximum send or receive data rate for multicast, default 100 */ public final void setRate (long value) { throw new UnsupportedOperationException (); } /** * @see #setRecoveryInterval(long) * * @return the RecoveryIntervall. */ public final long getRecoveryInterval () { return base.getsockopt(zmq.ZMQ.ZMQ_RECOVERY_IVL); } /** * The 'ZMQ_RECOVERY_IVL' option shall set the recovery interval for multicast transports * using the specified 'socket'. The recovery interval determines the maximum time in * seconds that a receiver can be absent from a multicast group before unrecoverable data * loss will occur. * * CAUTION: Excersize care when setting large recovery intervals as the data needed for * recovery will be held in memory. For example, a 1 minute recovery interval at a data rate * of 1Gbps requires a 7GB in-memory buffer. {Purpose of this Method} * * @param value recovery interval for multicast in milliseconds, default 10000 */ public final void setRecoveryInterval (long value) { throw new UnsupportedOperationException (); } /** * @see #setMulticastLoop(boolean) * * @return the Multicast Loop. */ @Deprecated public final boolean hasMulticastLoop () { return false; } /** * The 'ZMQ_MCAST_LOOP' option shall control whether data sent via multicast transports * using the specified 'socket' can also be received by the sending host via loopback. A * value of zero disables the loopback functionality, while the default value of 1 enables * the loopback functionality. Leaving multicast loopback enabled when it is not required * can have a negative impact on performance. Where possible, disable 'ZMQ_MCAST_LOOP' in * production environments. * * @param mcast_loop */ @Deprecated public final void setMulticastLoop (boolean mcast_loop) { throw new UnsupportedOperationException (); } /** * @see #setMulticastHops(long) * * @return the Multicast Hops. */ public final long getMulticastHops () { return base.getsockopt(zmq.ZMQ.ZMQ_MULTICAST_HOPS); } /** * Sets the time-to-live field in every multicast packet sent from this socket. * The default is 1 which means that the multicast packets don't leave the local * network. * * @param value time-to-live field in every multicast packet, default 1 */ public final void setMulticastHops (long value) { throw new UnsupportedOperationException (); } /** * @see #setReceiveTimeOut(int) * * @return the Receive Timeout in milliseconds. */ public final int getReceiveTimeOut() { return base.getsockopt(zmq.ZMQ.ZMQ_RCVTIMEO); } /** * Sets the timeout for receive operation on the socket. If the value is 0, recv * will return immediately, with null if there is no message to receive. * If the value is -1, it will block until a message is available. For all other * values, it will wait for a message for that amount of time before returning with * a null and an EAGAIN error. * * @param value Timeout for receive operation in milliseconds. Default -1 (infinite) */ public final void setReceiveTimeOut (int value) { base.setsockopt(zmq.ZMQ.ZMQ_RCVTIMEO, value); mayRaiseNot (ZError.ETERM); } /** * @see #setSendTimeOut(int) * * @return the Send Timeout in milliseconds. */ public final int getSendTimeOut() { return (int)base.getsockopt(zmq.ZMQ.ZMQ_SNDTIMEO); } /** * Sets the timeout for send operation on the socket. If the value is 0, send * will return immediately, with a false if the message cannot be sent. * If the value is -1, it will block until the message is sent. For all other * values, it will try to send the message for that amount of time before * returning with false and an EAGAIN error. * * @param value Timeout for send operation in milliseconds. Default -1 (infinite) */ public final void setSendTimeOut(int value) { base.setsockopt(zmq.ZMQ.ZMQ_SNDTIMEO, value); mayRaiseNot (ZError.ETERM); } /** * @see #setSendBufferSize(long) * * @return the kernel send buffer size. */ public final long getSendBufferSize() { return base.getsockopt(zmq.ZMQ.ZMQ_SNDBUF); } /** * The 'ZMQ_SNDBUF' option shall set the underlying kernel transmit buffer size for the * 'socket' to the specified size in bytes. A value of zero means leave the OS default * unchanged. For details please refer to your operating system documentation for the * 'SO_SNDBUF' socket option. * * @param value underlying kernel transmit buffer size for the 'socket' in bytes * A value of zero means leave the OS default unchanged. */ public final void setSendBufferSize(long value) { base.setsockopt(zmq.ZMQ.ZMQ_SNDBUF, (int)value); mayRaiseNot (ZError.ETERM); } /** * @see #setReceiveBufferSize(long) * * @return the kernel receive buffer size. */ public final long getReceiveBufferSize() { return base.getsockopt(zmq.ZMQ.ZMQ_RCVBUF); } /** * The 'ZMQ_RCVBUF' option shall set the underlying kernel receive buffer size for the * 'socket' to the specified size in bytes. * For details refer to your operating system documentation for the 'SO_RCVBUF' * socket option. * * @param value Underlying kernel receive buffer size for the 'socket' in bytes. * A value of zero means leave the OS default unchanged. */ public final void setReceiveBufferSize(long value) { base.setsockopt(zmq.ZMQ.ZMQ_RCVBUF, (int)value); mayRaiseNot (ZError.ETERM); } /** * The 'ZMQ_RCVMORE' option shall return a boolean value indicating if the multi-part * message currently being read from the specified 'socket' has more message parts to * follow. If there are no message parts to follow or if the message currently being read is * not a multi-part message a value of zero shall be returned. Otherwise, a value of 1 shall * be returned. * * @return true if there are more messages to receive. */ public final boolean hasReceiveMore () { return base.getsockopt (zmq.ZMQ.ZMQ_RCVMORE) == 1; } /** * The 'ZMQ_FD' option shall retrieve file descriptor associated with the 0MQ * socket. The descriptor can be used to integrate 0MQ socket into an existing * event loop. It should never be used for anything else than polling -- such as * reading or writing. The descriptor signals edge-triggered IN event when * something has happened within the 0MQ socket. It does not necessarily mean that * the messages can be read or written. Check ZMQ_EVENTS option to find out whether * the 0MQ socket is readable or writeable. * * @return the underlying file descriptor. */ public final SelectableChannel getFD() { return (SelectableChannel)base.getsockoptx(zmq.ZMQ.ZMQ_FD); } /** * The 'ZMQ_EVENTS' option shall retrieve event flags for the specified socket. * If a message can be read from the socket ZMQ_POLLIN flag is set. If message can * be written to the socket ZMQ_POLLOUT flag is set. * * @return the mask of outstanding events. */ public final int getEvents() { return base.getsockopt(zmq.ZMQ.ZMQ_EVENTS); } /** * The 'ZMQ_SUBSCRIBE' option shall establish a new message filter on a 'ZMQ_SUB' socket. * Newly created 'ZMQ_SUB' sockets shall filter out all incoming messages, therefore you * should call this option to establish an initial message filter. * * An empty 'option_value' of length zero shall subscribe to all incoming messages. A * non-empty 'option_value' shall subscribe to all messages beginning with the specified * prefix. Mutiple filters may be attached to a single 'ZMQ_SUB' socket, in which case a * message shall be accepted if it matches at least one filter. * * @param topic */ public final void subscribe(byte[] topic) { base.setsockopt(zmq.ZMQ.ZMQ_SUBSCRIBE, topic); mayRaiseNot (ZError.ETERM); } /** * The 'ZMQ_UNSUBSCRIBE' option shall remove an existing message filter on a 'ZMQ_SUB' * socket. The filter specified must match an existing filter previously established with * the 'ZMQ_SUBSCRIBE' option. If the socket has several instances of the same filter * attached the 'ZMQ_UNSUBSCRIBE' option shall remove only one instance, leaving the rest in * place and functional. * * @param topic */ public final void unsubscribe(byte[] topic) { base.setsockopt(zmq.ZMQ.ZMQ_UNSUBSCRIBE, topic); mayRaiseNot (ZError.ETERM); } /** * Set custom Encoder * @param cls */ public final void setEncoder(Class<? extends EncoderBase> cls) { base.setsockopt(zmq.ZMQ.ZMQ_ENCODER, cls); } /** * Set custom Decoder * @param cls */ public final void setDecoder(Class<? extends DecoderBase> cls) { base.setsockopt(zmq.ZMQ.ZMQ_DECODER, cls); } /** * Sets the ROUTER socket behavior when an unroutable message is encountered. * * @param mandatory A value of false is the default and discards the message silently when it cannot be routed. * A value of true returns an EHOSTUNREACH error code if the message cannot be routed. */ public final void setRouterMandatory (boolean mandatory) { base.setsockopt (zmq.ZMQ.ZMQ_ROUTER_MANDATORY, mandatory ? 1 : 0); mayRaiseNot (ZError.ETERM); } /** * Sets the XPUB socket behavior on new subscriptions and unsubscriptions. * * @param verbose A value of false is the default and passes only new subscription messages to upstream. * A value of true passes all subscription messages upstream. */ public final void setXpubVerbose(boolean verbose) { base.setsockopt(zmq.ZMQ.ZMQ_XPUB_VERBOSE, verbose ? 1 : 0); mayRaiseNot (ZError.ETERM); } /** * @see #setIPv4Only (boolean) * * @return the IPV4ONLY */ public final boolean getIPv4Only () { return base.getsockopt (zmq.ZMQ.ZMQ_IPV4ONLY) == 1; } /** * The 'ZMQ_IPV4ONLY' option shall set the underlying native socket type. * An IPv6 socket lets applications connect to and accept connections from both IPv4 and IPv6 hosts. * * @param v4only A value of true will use IPv4 sockets, while the value of false will use IPv6 sockets */ public void setIPv4Only (boolean v4only) { base.setsockopt (zmq.ZMQ.ZMQ_IPV4ONLY, v4only ? 1 : 0); mayRaiseNot (ZError.ETERM); } /** * @see #setTCPKeepAlive(int) * * @return the keep alive setting. */ public int getTCPKeepAlive() { return base.getsockopt(zmq.ZMQ.ZMQ_TCP_KEEPALIVE); } /** * Override SO_KEEPALIVE socket option (where supported by OS) to enable keep-alive packets for a socket * connection. Possible values are -1, 0, 1. The default value -1 will skip all overrides and do the OS default. * * @param optVal The value of 'ZMQ_TCP_KEEPALIVE' to turn TCP keepalives on (1) or off (0). */ public void setTCPKeepAlive(int optVal) { base.setsockopt(zmq.ZMQ.ZMQ_TCP_KEEPALIVE, (int)optVal); mayRaiseNot (ZError.ETERM); } /** * Bind to network interface. Start listening for new connections. * * @param addr * the endpoint to bind to. */ public final int bind (String addr) { return bind (addr, DYNFROM, DYNTO); } /** * Bind to network interface. Start listening for new connections. * * @param addr * the endpoint to bind to. * @param min * The minimum port in the range of ports to try. * @param max * The maximum port in the range of ports to try. */ private final int bind (String addr, int min, int max) { if (addr.endsWith (":*")) { int port = min; String prefix = addr.substring (0, addr.lastIndexOf (':') + 1); while (port <= max) { addr = prefix + port; // Try to bind on the next plausible port if (base.bind (addr)) return port; port++; } } else { if (base.bind(addr)) { int port = 0; try { port = Integer.parseInt ( addr.substring (addr.lastIndexOf (':') + 1)); } catch (NumberFormatException e) { } return port; } } mayRaise (); return -1; } /** * Bind to network interface to a random port. Start listening for new * connections. * * @param addr * the endpoint to bind to. */ public int bindToRandomPort (String addr) { return bind (addr + ":*", DYNFROM, DYNTO); } /** * Bind to network interface to a random port. Start listening for new * connections. * * @param addr * the endpoint to bind to. * @param min * The minimum port in the range of ports to try. * @param max * The maximum port in the range of ports to try. */ public int bindToRandomPort (String addr, int min, int max) { return bind (addr + ":*", min, max); } /** * Connect to remote application. * * @param addr * the endpoint to connect to. */ public final void connect (String addr) { base.connect (addr); mayRaise (); } /** * Disconnect to remote application. * * @param addr * the endpoint to disconnect to. */ public final boolean disconnect (String addr) { boolean ret = base.term_endpoint (addr); mayRaise (); return ret; } public final boolean send (String data) { return send (data.getBytes (), 0); } public final boolean sendMore (String data) { return send(data.getBytes (), zmq.ZMQ.ZMQ_SNDMORE); } public final boolean send (String data, int flags) { return send(data.getBytes (), flags); } public final boolean send (byte[] data) { return send(data, 0); } public final boolean sendMore (byte[] data) { return send(data, zmq.ZMQ.ZMQ_SNDMORE); } public final boolean send (byte[] data, int flags) { zmq.Msg msg = new zmq.Msg(data); if (base.send(msg, flags)) return true; mayRaise (); return false; } /** * Send a message * * @param bb ByteBuffer payload * @param flags the flags to apply to the send operation * @return the number of bytes sent, -1 on error */ public final boolean sendByteBuffer (ByteBuffer data, int flags) { zmq.Msg msg = new zmq.Msg(data); if (base.send(msg, flags)) return true; mayRaise (); return false; } /** * Receive a message. * * @return the message received, as an array of bytes; null on error. */ public final byte[] recv () { return recv (0); } /** * Receive a message. * * @param flags * the flags to apply to the receive operation. * @return the message received, as an array of bytes; null on error. */ public final byte[] recv (int flags) { zmq.Msg msg = base.recv(flags); if (msg != null) { return msg.data(); } mayRaise (); return null; } /** * Receive a message in to a specified buffer. * * @param buffer * byte[] to copy zmq message payload in to. * @param offset * offset in buffer to write data * @param len * max bytes to write to buffer. * If len is smaller than the incoming message size, * the message will be truncated. * @param flags * the flags to apply to the receive operation. * @return the number of bytes read, -1 on error */ public final int recv (byte[] buffer, int offset, int len, int flags) { zmq.Msg msg = base.recv (flags); if (msg != null) { int size = Math.min (msg.size (), len); System.arraycopy (msg.data (), 0, buffer, offset, size); return size; } mayRaise (); return -1; } /** * Receive a message into the specified ByteBuffer * * @param buffer the buffer to copy the zmq message payload into * @param flags the flags to apply to the receive operation * @return the number of bytes read, -1 on error */ public final int recvByteBuffer (ByteBuffer buffer, int flags) { zmq.Msg msg = base.recv (flags); if (msg != null) { buffer.put(msg.data()); return msg.size(); } mayRaise (); return -1; } /** * * @return the message received, as a String object; null on no message. */ public final String recvStr () { return recvStr (0); } /** * * @param flags the flags to apply to the receive operation. * @return the message received, as a String object; null on no message. */ public final String recvStr (int flags) { byte [] msg = recv(flags); if (msg != null) { return new String (msg); } return null; } public boolean monitor (String addr, int events) { return base.monitor (addr, events); } } public static class Poller { /** * These values can be ORed to specify what we want to poll for. */ public static final int POLLIN = zmq.ZMQ.ZMQ_POLLIN; public static final int POLLOUT = zmq.ZMQ.ZMQ_POLLOUT; public static final int POLLERR = zmq.ZMQ.ZMQ_POLLERR; private static final int SIZE_DEFAULT = 32; private static final int SIZE_INCREMENT = 16; private PollItem [] items; private long timeout; private int next; public Poller (int size) { this (null, size); } /** * Class constructor. * * @param context * a 0MQ context previously created. * @param size * the number of Sockets this poller will contain. */ protected Poller (Context context, int size) { items = new PollItem[size]; timeout = -1L; next = 0; } /** * Class constructor. * * @param context * a 0MQ context previously created. */ protected Poller (Context context) { this(context, SIZE_DEFAULT); } /** * Register a Socket for polling on all events. * * @param socket * the Socket we are registering. * @return the index identifying this Socket in the poll set. */ public int register (Socket socket) { return register (socket, POLLIN | POLLOUT | POLLERR); } /** * Register a Socket for polling on the specified events. * * Automatically grow the internal representation if needed. * * @param socket * the Socket we are registering. * @param events * a mask composed by XORing POLLIN, POLLOUT and POLLERR. * @return the index identifying this Socket in the poll set. */ public int register (Socket socket, int events) { return insert (new PollItem (socket, events)); } /** * Register a Socket for polling on the specified events. * * Automatically grow the internal representation if needed. * * @param channel * the Channel we are registering. * @param events * a mask composed by XORing POLLIN, POLLOUT and POLLERR. * @return the index identifying this Channel in the poll set. */ public int register (SelectableChannel channel, int events) { return insert (new PollItem (channel, events)); } /** * Register a Channel for polling on the specified events. * * Automatically grow the internal representation if needed. * * @param item * the PollItem we are registering. * @return the index identifying this Channel in the poll set. */ public int register (PollItem item) { return insert (item); } private int insert (PollItem item) { int pos = next++; if (pos == items.length) { PollItem[] nitems = new PollItem[items.length + SIZE_INCREMENT]; System.arraycopy (items, 0, nitems, 0, items.length); items = nitems; } items [pos] = item; return pos; } /** * Unregister a Socket for polling on the specified events. * * @param socket * the Socket to be unregistered */ public void unregister (Socket socket) { for (int pos = 0; pos < items.length ;pos++) { PollItem item = items[pos]; if (item.getSocket () == socket) { remove (pos); break; } } } /** * Unregister a Socket for polling on the specified events. * * @param channel * the Socket to be unregistered */ public void unregister (SelectableChannel channel) { for (int pos = 0; pos < items.length ;pos++) { PollItem item = items[pos]; if (item.getRawSocket () == channel) { remove (pos); break; } } } private void remove (int pos) { next--; if (pos != next) items [pos] = items [next]; items [next] = null; } /** * Get the PollItem associated with an index. * * @param index * the desired index. * @return the PollItem associated with that index (or null). */ public PollItem getItem (int index) { if (index < 0 || index >= this.next) return null; return this.items[index]; } /** * Get the socket associated with an index. * * @param index * the desired index. * @return the Socket associated with that index (or null). */ public Socket getSocket (int index) { if (index < 0 || index >= this.next) return null; return items[index].getSocket (); } /** * Get the current poll timeout. * * @return the current poll timeout in milliseconds. * @deprecated Timeout handling has been moved to the poll() methods. */ public long getTimeout () { return this.timeout; } /** * Set the poll timeout. * * @param timeout * the desired poll timeout in milliseconds. * @deprecated Timeout handling has been moved to the poll() methods. */ public void setTimeout (long timeout) { if (timeout < -1) return; this.timeout = timeout; } /** * Get the current poll set size. * * @return the current poll set size. */ public int getSize () { return items.length; } /** * Get the index for the next position in the poll set size. * * @return the index for the next position in the poll set size. */ public int getNext () { return this.next; } /** * Issue a poll call. If the poller's internal timeout value * has been set, use that value as timeout; otherwise, block * indefinitely. * * @return how many objects where signaled by poll (). */ public int poll () { long tout = -1L; if (this.timeout > -1L) { tout = this.timeout; } return poll(tout); } /** * Issue a poll call, using the specified timeout value. * <p> * Since ZeroMQ 3.0, the timeout parameter is in <i>milliseconds<i>, * but prior to this the unit was <i>microseconds</i>. * * @param tout * the timeout, as per zmq_poll (); * if -1, it will block indefinitely until an event * happens; if 0, it will return immediately; * otherwise, it will wait for at most that many * milliseconds/microseconds (see above). * * @see "http://api.zeromq.org/3-0:zmq-poll" * * @return how many objects where signaled by poll () */ public int poll(long tout) { zmq.PollItem[] pollItems = new zmq.PollItem[next]; for (int i = 0; i < next; i++) pollItems[i] = items[i].base (); return zmq.ZMQ.zmq_poll (pollItems, next, tout); } /** * Check whether the specified element in the poll set was signaled for input. * * @param index * * @return true if the element was signaled. */ public boolean pollin (int index) { if (index < 0 || index >= this.next) return false; return items [index].isReadable(); } /** * Check whether the specified element in the poll set was signaled for output. * * @param index * * @return true if the element was signaled. */ public boolean pollout (int index) { if (index < 0 || index >= this.next) return false; return items [index].isWritable (); } /** * Check whether the specified element in the poll set was signaled for error. * * @param index * * @return true if the element was signaled. */ public boolean pollerr (int index) { if (index < 0 || index >= this.next) return false; return items [index].isError(); } } public static class PollItem { private final zmq.PollItem base; private final Socket socket; public PollItem (Socket socket, int ops) { this.socket = socket; base = new zmq.PollItem (socket.base, ops); } public PollItem (SelectableChannel channel, int ops) { base = new zmq.PollItem (channel, ops); socket = null; } protected final zmq.PollItem base() { return base; } public final SelectableChannel getRawSocket () { return base.getRawSocket (); } public final Socket getSocket() { return socket; } public final boolean isReadable() { return base.isReadable(); } public final boolean isWritable() { return base.isWritable (); } public final boolean isError () { return base.isError (); } public final int readyOps () { return base.readyOps (); } @Override public boolean equals (Object obj) { if (!(obj instanceof PollItem)) return false; PollItem target = (PollItem) obj; if (socket != null && socket == target.socket) return true; if (getRawSocket () != null && getRawSocket () == target.getRawSocket ()) return true; return false; } } public enum Error { ENOTSUP(ZError.ENOTSUP), EPROTONOSUPPORT(ZError.EPROTONOSUPPORT), ENOBUFS(ZError.ENOBUFS), ENETDOWN(ZError.ENETDOWN), EADDRINUSE(ZError.EADDRINUSE), EADDRNOTAVAIL(ZError.EADDRNOTAVAIL), ECONNREFUSED(ZError.ECONNREFUSED), EINPROGRESS(ZError.EINPROGRESS), EMTHREAD(ZError.EMTHREAD), EFSM(ZError.EFSM), ENOCOMPATPROTO(ZError.ENOCOMPATPROTO), ETERM(ZError.ETERM); private final long code; Error(long code) { this.code = code; } public long getCode() { return code; } public static Error findByCode(int code) { for (Error e : Error.class.getEnumConstants()) { if (e.getCode() == code) { return e; } } throw new IllegalArgumentException("Unknown " + Error.class.getName() + " enum code:" + code); } } @Deprecated public static boolean device (int type_, Socket frontend, Socket backend) { return zmq.ZMQ.zmq_proxy (frontend.base, backend.base, null); } /** * Starts the built-in ØMQ proxy in the current application thread. * The proxy connects a frontend socket to a backend socket. Conceptually, data flows from frontend to backend. * Depending on the socket types, replies may flow in the opposite direction. The direction is conceptual only; * the proxy is fully symmetric and there is no technical difference between frontend and backend. * * Before calling ZMQ.proxy() you must set any socket options, and connect or bind both frontend and backend sockets. * The two conventional proxy models are: * * ZMQ.proxy() runs in the current thread and returns only if/when the current context is closed. * @param frontend ZMQ.Socket * @param backend ZMQ.Socket * @param capture If the capture socket is not NULL, the proxy shall send all messages, received on both * frontend and backend, to the capture socket. The capture socket should be a * ZMQ_PUB, ZMQ_DEALER, ZMQ_PUSH, or ZMQ_PAIR socket. */ public static boolean proxy (Socket frontend, Socket backend, Socket capture) { return zmq.ZMQ.zmq_proxy (frontend.base, backend.base, capture != null ? capture.base: null); } public static int poll(PollItem[] items, long timeout) { return poll(items, items.length, timeout); } public static int poll(PollItem[] items, int count, long timeout) { zmq.PollItem[] items_ = new zmq.PollItem[count]; for (int i = 0; i < count; i++) { items_[i] = items[i].base; } return zmq.ZMQ.zmq_poll(items_, count, timeout); } /** * @return Major version number of the ZMQ library. */ public static int getMajorVersion () { return zmq.ZMQ.ZMQ_VERSION_MAJOR; } /** * @return Major version number of the ZMQ library. */ public static int getMinorVersion () { return zmq.ZMQ.ZMQ_VERSION_MINOR; } /** * @return Major version number of the ZMQ library. */ public static int getPatchVersion () { return zmq.ZMQ.ZMQ_VERSION_PATCH; } /** * @return Full version number of the ZMQ library used for comparing versions. */ public static int getFullVersion() { return zmq.ZMQ.ZMQ_MAKE_VERSION(zmq.ZMQ.ZMQ_VERSION_MAJOR, zmq.ZMQ.ZMQ_VERSION_MINOR, zmq.ZMQ.ZMQ_VERSION_PATCH); } /** * @param major Version major component. * @param minor Version minor component. * @param patch Version patch component. * * @return Comparible single int version number. */ public static int makeVersion ( final int major, final int minor, final int patch ) { return zmq.ZMQ.ZMQ_MAKE_VERSION ( major, minor, patch ); } /** * @return String version number in the form major.minor.patch. */ public static String getVersionString() { return "" + zmq.ZMQ.ZMQ_VERSION_MAJOR + "." + zmq.ZMQ.ZMQ_VERSION_MINOR + "." + zmq.ZMQ.ZMQ_VERSION_PATCH; } }
src/main/java/org/zeromq/ZMQ.java
/* Copyright (c) 1991-2011 iMatix Corporation <www.imatix.com> Copyright other contributors as noted in the AUTHORS file. This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.zeromq; import java.nio.ByteBuffer; import java.nio.channels.SelectableChannel; import zmq.Ctx; import zmq.DecoderBase; import zmq.EncoderBase; import zmq.SocketBase; import zmq.ZError; public class ZMQ { /** * Socket flag to indicate that more message parts are coming. */ public static final int SNDMORE = zmq.ZMQ.ZMQ_SNDMORE; // Values for flags in Socket's send and recv functions. /** * Socket flag to indicate a nonblocking send or recv mode. */ public static final int DONTWAIT = zmq.ZMQ.ZMQ_DONTWAIT; public static final int NOBLOCK = zmq.ZMQ.ZMQ_DONTWAIT; // Socket types, used when creating a Socket. /** * Flag to specify a exclusive pair of sockets. */ public static final int PAIR = zmq.ZMQ.ZMQ_PAIR; /** * Flag to specify a PUB socket, receiving side must be a SUB or XSUB. */ public static final int PUB = zmq.ZMQ.ZMQ_PUB; /** * Flag to specify the receiving part of the PUB or XPUB socket. */ public static final int SUB = zmq.ZMQ.ZMQ_SUB; /** * Flag to specify a REQ socket, receiving side must be a REP. */ public static final int REQ = zmq.ZMQ.ZMQ_REQ; /** * Flag to specify the receiving part of a REQ socket. */ public static final int REP = zmq.ZMQ.ZMQ_REP; /** * Flag to specify a DEALER socket (aka XREQ). * DEALER is really a combined ventilator / sink * that does load-balancing on output and fair-queuing on input * with no other semantics. It is the only socket type that lets * you shuffle messages out to N nodes and shuffle the replies * back, in a raw bidirectional asynch pattern. */ public static final int DEALER = zmq.ZMQ.ZMQ_DEALER; /** * Old alias for DEALER flag. * Flag to specify a XREQ socket, receiving side must be a XREP. * * @deprecated As of release 3.0 of zeromq, replaced by {@link #DEALER} */ public static final int XREQ = DEALER; /** * Flag to specify ROUTER socket (aka XREP). * ROUTER is the socket that creates and consumes request-reply * routing envelopes. It is the only socket type that lets you route * messages to specific connections if you know their identities. */ public static final int ROUTER = zmq.ZMQ.ZMQ_ROUTER; /** * Old alias for ROUTER flag. * Flag to specify the receiving part of a XREQ socket. * * @deprecated As of release 3.0 of zeromq, replaced by {@link #ROUTER} */ public static final int XREP = ROUTER; /** * Flag to specify the receiving part of a PUSH socket. */ public static final int PULL = zmq.ZMQ.ZMQ_PULL; /** * Flag to specify a PUSH socket, receiving side must be a PULL. */ public static final int PUSH = zmq.ZMQ.ZMQ_PUSH; /** * Flag to specify a XPUB socket, receiving side must be a SUB or XSUB. * Subscriptions can be received as a message. Subscriptions start with * a '1' byte. Unsubscriptions start with a '0' byte. */ public static final int XPUB = zmq.ZMQ.ZMQ_XPUB; /** * Flag to specify the receiving part of the PUB or XPUB socket. Allows */ public static final int XSUB = zmq.ZMQ.ZMQ_XSUB; /** * Flag to specify a STREAMER device. */ public static final int STREAMER = zmq.ZMQ.ZMQ_STREAMER ; /** * Flag to specify a FORWARDER device. */ public static final int FORWARDER = zmq.ZMQ.ZMQ_FORWARDER ; /** * Flag to specify a QUEUE device. */ public static final int QUEUE = zmq.ZMQ.ZMQ_QUEUE ; /** * @see org.zeromq.ZMQ#PULL */ @Deprecated public static final int UPSTREAM = PULL; /** * @see org.zeromq.ZMQ#PUSH */ @Deprecated public static final int DOWNSTREAM = PUSH; /** * ZMQ Events */ public static final int EVENT_CONNECTED = zmq.ZMQ.ZMQ_EVENT_CONNECTED; public static final int EVENT_DELAYED = zmq.ZMQ.ZMQ_EVENT_CONNECT_DELAYED; public static final int EVENT_RETRIED = zmq.ZMQ.ZMQ_EVENT_CONNECT_RETRIED; public static final int EVENT_CONNECT_FAILED = zmq.ZMQ.ZMQ_EVENT_CONNECT_FAILED; public static final int EVENT_LISTENING = zmq.ZMQ.ZMQ_EVENT_LISTENING; public static final int EVENT_BIND_FAILED = zmq.ZMQ.ZMQ_EVENT_BIND_FAILED; public static final int EVENT_ACCEPTED = zmq.ZMQ.ZMQ_EVENT_ACCEPTED; public static final int EVENT_ACCEPT_FAILED = zmq.ZMQ.ZMQ_EVENT_ACCEPT_FAILED; public static final int EVENT_CLOSED = zmq.ZMQ.ZMQ_EVENT_CLOSED; public static final int EVENT_CLOSE_FAILED = zmq.ZMQ.ZMQ_EVENT_CLOSE_FAILED; public static final int EVENT_DISCONNECTED = zmq.ZMQ.ZMQ_EVENT_DISCONNECTED; public static final int EVENT_ALL = zmq.ZMQ.ZMQ_EVENT_ALL; /** * Create a new Context. * * @param ioThreads * Number of threads to use, usually 1 is sufficient for most use cases. * @return the Context */ public static Context context(int ioThreads) { return new Context(ioThreads); } public static class Context { private final Ctx ctx; /** * Class constructor. * * @param ioThreads * size of the threads pool to handle I/O operations. */ protected Context(int ioThreads) { ctx = zmq.ZMQ.zmq_init(ioThreads); } /** * This is an explicit "destructor". It can be called to ensure the corresponding 0MQ * Context has been disposed of. */ public void term() { ctx.terminate(); } /** * Create a new Socket within this context. * * @param type * the socket type. * @return the newly created Socket. */ public Socket socket(int type) { return new Socket(this, type); } /** * Create a new Poller within this context, with a default size. * * @return the newly created Poller. * @deprecated Use poller constructor */ public Poller poller () { return new Poller (this); } /** * Create a new Poller within this context, with a specified initial size. * * @param size * the poller initial size. * @return the newly created Poller. * @deprecated Use poller constructor */ public Poller poller (int size) { return new Poller (this, size); } } public static class Socket { // This port range is defined by IANA for dynamic or private ports // We use this when choosing a port for dynamic binding. private static final int DYNFROM = 0xc000; private static final int DYNTO = 0xffff; private final Ctx ctx; private final SocketBase base; /** * Class constructor. * * @param context * a 0MQ context previously created. * @param type * the socket type. */ protected Socket(Context context, int type) { ctx = context.ctx; base = ctx.create_socket(type); mayRaise(); } protected Socket(SocketBase base_) { ctx = null; base = base_; } protected SocketBase base() { return base; } private final static void mayRaise () { if (!ZError.is (0) && !ZError.is (ZError.EAGAIN)) throw new ZMQException (ZError.errno ()); } private final static void mayRaiseNot (int codeToIgnore) { if (!ZError.is (codeToIgnore)) mayRaise (); } /** * This is an explicit "destructor". It can be called to ensure the corresponding 0MQ Socket * has been disposed of. */ public final void close() { base.close(); } /** * The 'ZMQ_TYPE option shall retrieve the socket type for the specified * 'socket'. The socket type is specified at socket creation time and * cannot be modified afterwards. * * @return the socket type. */ public final int getType () { return base.getsockopt(zmq.ZMQ.ZMQ_TYPE); } /** * @see #setLinger(long) * * @return the linger period. */ public final long getLinger() { return base.getsockopt(zmq.ZMQ.ZMQ_LINGER); } /** * The 'ZMQ_LINGER' option shall retrieve the period for pending outbound * messages to linger in memory after closing the socket. Value of -1 means * infinite. Pending messages will be kept until they are fully transferred to * the peer. Value of 0 means that all the pending messages are dropped immediately * when socket is closed. Positive value means number of milliseconds to keep * trying to send the pending messages before discarding them. * * @param value * the linger period in milliseconds. */ public final void setLinger (long value) { base.setsockopt (zmq.ZMQ.ZMQ_LINGER, (int) value); mayRaiseNot (ZError.ETERM); } /** * @see #setReconnectIVL(long) * * @return the reconnectIVL. */ public final long getReconnectIVL() { return base.getsockopt(zmq.ZMQ.ZMQ_RECONNECT_IVL); } /** */ public final void setReconnectIVL(long value) { base.setsockopt(zmq.ZMQ.ZMQ_RECONNECT_IVL, (int)value); mayRaiseNot (ZError.ETERM); } /** * @see #setBacklog(long) * * @return the backlog. */ public final long getBacklog() { return base.getsockopt(zmq.ZMQ.ZMQ_BACKLOG); } /** */ public final void setBacklog(long value) { base.setsockopt(zmq.ZMQ.ZMQ_BACKLOG, (int)value); mayRaiseNot (ZError.ETERM); } /** * @see #setReconnectIVLMax(long) * * @return the reconnectIVLMax. */ public final long getReconnectIVLMax () { return base.getsockopt(zmq.ZMQ.ZMQ_RECONNECT_IVL_MAX); } /** */ public final void setReconnectIVLMax (long value) { base.setsockopt(zmq.ZMQ.ZMQ_RECONNECT_IVL_MAX, (int)value); mayRaiseNot (ZError.ETERM); } /** * @see #setMaxMsgSize(long) * * @return the maxMsgSize. */ public final long getMaxMsgSize() { return (Long)base.getsockoptx(zmq.ZMQ.ZMQ_MAXMSGSIZE); } /** */ public final void setMaxMsgSize(long value) { base.setsockopt(zmq.ZMQ.ZMQ_MAXMSGSIZE, value); mayRaiseNot (ZError.ETERM); } /** * @see #setSndHWM(long) * * @return the SndHWM. */ public final long getSndHWM() { return base.getsockopt(zmq.ZMQ.ZMQ_SNDHWM); } /** */ public final void setSndHWM(long value) { base.setsockopt(zmq.ZMQ.ZMQ_SNDHWM, (int)value); mayRaiseNot (ZError.ETERM); } /** * @see #setRcvHWM(long) * * @return the recvHWM period. */ public final long getRcvHWM() { return base.getsockopt(zmq.ZMQ.ZMQ_RCVHWM); } /** */ public final void setRcvHWM(long value) { base.setsockopt(zmq.ZMQ.ZMQ_RCVHWM, (int)value); mayRaiseNot (ZError.ETERM); } /** * @see #setHWM(long) * * @return the High Water Mark. */ @Deprecated public final long getHWM() { return -1; } /** * The 'ZMQ_HWM' option shall set the high water mark for the specified 'socket'. The high * water mark is a hard limit on the maximum number of outstanding messages 0MQ shall queue * in memory for any single peer that the specified 'socket' is communicating with. * * If this limit has been reached the socket shall enter an exceptional state and depending * on the socket type, 0MQ shall take appropriate action such as blocking or dropping sent * messages. Refer to the individual socket descriptions in the man page of zmq_socket[3] for * details on the exact action taken for each socket type. * * @param hwm * the number of messages to queue. */ public final void setHWM(long hwm) { setSndHWM (hwm); setRcvHWM (hwm); } /** * @see #setSwap(long) * * @return the number of messages to swap at most. */ @Deprecated public final long getSwap() { // not support at zeromq 3 return -1L; } /** * Get the Swap. The 'ZMQ_SWAP' option shall set the disk offload (swap) size for the * specified 'socket'. A socket which has 'ZMQ_SWAP' set to a non-zero value may exceed its * high water mark; in this case outstanding messages shall be offloaded to storage on disk * rather than held in memory. * * @param value * The value of 'ZMQ_SWAP' defines the maximum size of the swap space in bytes. */ @Deprecated public final void setSwap(long value) { throw new UnsupportedOperationException (); } /** * @see #setAffinity(long) * * @return the affinity. */ public final long getAffinity() { return (Long)base.getsockoptx(zmq.ZMQ.ZMQ_AFFINITY); } /** * Get the Affinity. The 'ZMQ_AFFINITY' option shall set the I/O thread affinity for newly * created connections on the specified 'socket'. * * Affinity determines which threads from the 0MQ I/O thread pool associated with the * socket's _context_ shall handle newly created connections. A value of zero specifies no * affinity, meaning that work shall be distributed fairly among all 0MQ I/O threads in the * thread pool. For non-zero values, the lowest bit corresponds to thread 1, second lowest * bit to thread 2 and so on. For example, a value of 3 specifies that subsequent * connections on 'socket' shall be handled exclusively by I/O threads 1 and 2. * * See also in the man page of zmq_init[3] for details on allocating the number of I/O threads for a * specific _context_. * * @param value * the io_thread affinity. */ public final void setAffinity (long value) { base.setsockopt(zmq.ZMQ.ZMQ_AFFINITY, value); mayRaiseNot (ZError.ETERM); } /** * @see #setIdentity(byte[]) * * @return the Identitiy. */ public final byte[] getIdentity() { return (byte[]) base.getsockoptx(zmq.ZMQ.ZMQ_IDENTITY); } /** * The 'ZMQ_IDENTITY' option shall set the identity of the specified 'socket'. Socket * identity determines if existing 0MQ infastructure (_message queues_, _forwarding * devices_) shall be identified with a specific application and persist across multiple * runs of the application. * * If the socket has no identity, each run of an application is completely separate from * other runs. However, with identity set the socket shall re-use any existing 0MQ * infrastructure configured by the previous run(s). Thus the application may receive * messages that were sent in the meantime, _message queue_ limits shall be shared with * previous run(s) and so on. * * Identity should be at least one byte and at most 255 bytes long. Identities starting with * binary zero are reserved for use by 0MQ infrastructure. * * @param identity */ public final void setIdentity(byte[] identity) { base.setsockopt(zmq.ZMQ.ZMQ_IDENTITY, identity); mayRaiseNot (ZError.ETERM); } /** * @see #setRate(long) * * @return the Rate. */ public final long getRate() { return base.getsockopt(zmq.ZMQ.ZMQ_RATE); } /** * The 'ZMQ_RATE' option shall set the maximum send or receive data rate for multicast * transports such as in the man page of zmq_pgm[7] using the specified 'socket'. * * @param value maximum send or receive data rate for multicast, default 100 */ public final void setRate (long value) { throw new UnsupportedOperationException (); } /** * @see #setRecoveryInterval(long) * * @return the RecoveryIntervall. */ public final long getRecoveryInterval () { return base.getsockopt(zmq.ZMQ.ZMQ_RECOVERY_IVL); } /** * The 'ZMQ_RECOVERY_IVL' option shall set the recovery interval for multicast transports * using the specified 'socket'. The recovery interval determines the maximum time in * seconds that a receiver can be absent from a multicast group before unrecoverable data * loss will occur. * * CAUTION: Excersize care when setting large recovery intervals as the data needed for * recovery will be held in memory. For example, a 1 minute recovery interval at a data rate * of 1Gbps requires a 7GB in-memory buffer. {Purpose of this Method} * * @param value recovery interval for multicast in milliseconds, default 10000 */ public final void setRecoveryInterval (long value) { throw new UnsupportedOperationException (); } /** * @see #setMulticastLoop(boolean) * * @return the Multicast Loop. */ @Deprecated public final boolean hasMulticastLoop () { return false; } /** * The 'ZMQ_MCAST_LOOP' option shall control whether data sent via multicast transports * using the specified 'socket' can also be received by the sending host via loopback. A * value of zero disables the loopback functionality, while the default value of 1 enables * the loopback functionality. Leaving multicast loopback enabled when it is not required * can have a negative impact on performance. Where possible, disable 'ZMQ_MCAST_LOOP' in * production environments. * * @param mcast_loop */ @Deprecated public final void setMulticastLoop (boolean mcast_loop) { throw new UnsupportedOperationException (); } /** * @see #setMulticastHops(long) * * @return the Multicast Hops. */ public final long getMulticastHops () { return base.getsockopt(zmq.ZMQ.ZMQ_MULTICAST_HOPS); } /** * Sets the time-to-live field in every multicast packet sent from this socket. * The default is 1 which means that the multicast packets don't leave the local * network. * * @param value time-to-live field in every multicast packet, default 1 */ public final void setMulticastHops (long value) { throw new UnsupportedOperationException (); } /** * @see #setReceiveTimeOut(int) * * @return the Receive Timeout in milliseconds. */ public final int getReceiveTimeOut() { return base.getsockopt(zmq.ZMQ.ZMQ_RCVTIMEO); } /** * Sets the timeout for receive operation on the socket. If the value is 0, recv * will return immediately, with null if there is no message to receive. * If the value is -1, it will block until a message is available. For all other * values, it will wait for a message for that amount of time before returning with * a null and an EAGAIN error. * * @param value Timeout for receive operation in milliseconds. Default -1 (infinite) */ public final void setReceiveTimeOut (int value) { base.setsockopt(zmq.ZMQ.ZMQ_RCVTIMEO, value); mayRaiseNot (ZError.ETERM); } /** * @see #setSendTimeOut(int) * * @return the Send Timeout in milliseconds. */ public final int getSendTimeOut() { return (int)base.getsockopt(zmq.ZMQ.ZMQ_SNDTIMEO); } /** * Sets the timeout for send operation on the socket. If the value is 0, send * will return immediately, with a false if the message cannot be sent. * If the value is -1, it will block until the message is sent. For all other * values, it will try to send the message for that amount of time before * returning with false and an EAGAIN error. * * @param value Timeout for send operation in milliseconds. Default -1 (infinite) */ public final void setSendTimeOut(int value) { base.setsockopt(zmq.ZMQ.ZMQ_SNDTIMEO, value); mayRaiseNot (ZError.ETERM); } /** * @see #setSendBufferSize(long) * * @return the kernel send buffer size. */ public final long getSendBufferSize() { return base.getsockopt(zmq.ZMQ.ZMQ_SNDBUF); } /** * The 'ZMQ_SNDBUF' option shall set the underlying kernel transmit buffer size for the * 'socket' to the specified size in bytes. A value of zero means leave the OS default * unchanged. For details please refer to your operating system documentation for the * 'SO_SNDBUF' socket option. * * @param value underlying kernel transmit buffer size for the 'socket' in bytes * A value of zero means leave the OS default unchanged. */ public final void setSendBufferSize(long value) { base.setsockopt(zmq.ZMQ.ZMQ_SNDBUF, (int)value); mayRaiseNot (ZError.ETERM); } /** * @see #setReceiveBufferSize(long) * * @return the kernel receive buffer size. */ public final long getReceiveBufferSize() { return base.getsockopt(zmq.ZMQ.ZMQ_RCVBUF); } /** * The 'ZMQ_RCVBUF' option shall set the underlying kernel receive buffer size for the * 'socket' to the specified size in bytes. * For details refer to your operating system documentation for the 'SO_RCVBUF' * socket option. * * @param value Underlying kernel receive buffer size for the 'socket' in bytes. * A value of zero means leave the OS default unchanged. */ public final void setReceiveBufferSize(long value) { base.setsockopt(zmq.ZMQ.ZMQ_RCVBUF, (int)value); mayRaiseNot (ZError.ETERM); } /** * The 'ZMQ_RCVMORE' option shall return a boolean value indicating if the multi-part * message currently being read from the specified 'socket' has more message parts to * follow. If there are no message parts to follow or if the message currently being read is * not a multi-part message a value of zero shall be returned. Otherwise, a value of 1 shall * be returned. * * @return true if there are more messages to receive. */ public final boolean hasReceiveMore () { return base.getsockopt (zmq.ZMQ.ZMQ_RCVMORE) == 1; } /** * The 'ZMQ_FD' option shall retrieve file descriptor associated with the 0MQ * socket. The descriptor can be used to integrate 0MQ socket into an existing * event loop. It should never be used for anything else than polling -- such as * reading or writing. The descriptor signals edge-triggered IN event when * something has happened within the 0MQ socket. It does not necessarily mean that * the messages can be read or written. Check ZMQ_EVENTS option to find out whether * the 0MQ socket is readable or writeable. * * @return the underlying file descriptor. */ public final SelectableChannel getFD() { return (SelectableChannel)base.getsockoptx(zmq.ZMQ.ZMQ_FD); } /** * The 'ZMQ_EVENTS' option shall retrieve event flags for the specified socket. * If a message can be read from the socket ZMQ_POLLIN flag is set. If message can * be written to the socket ZMQ_POLLOUT flag is set. * * @return the mask of outstanding events. */ public final int getEvents() { return base.getsockopt(zmq.ZMQ.ZMQ_EVENTS); } /** * The 'ZMQ_SUBSCRIBE' option shall establish a new message filter on a 'ZMQ_SUB' socket. * Newly created 'ZMQ_SUB' sockets shall filter out all incoming messages, therefore you * should call this option to establish an initial message filter. * * An empty 'option_value' of length zero shall subscribe to all incoming messages. A * non-empty 'option_value' shall subscribe to all messages beginning with the specified * prefix. Mutiple filters may be attached to a single 'ZMQ_SUB' socket, in which case a * message shall be accepted if it matches at least one filter. * * @param topic */ public final void subscribe(byte[] topic) { base.setsockopt(zmq.ZMQ.ZMQ_SUBSCRIBE, topic); mayRaiseNot (ZError.ETERM); } /** * The 'ZMQ_UNSUBSCRIBE' option shall remove an existing message filter on a 'ZMQ_SUB' * socket. The filter specified must match an existing filter previously established with * the 'ZMQ_SUBSCRIBE' option. If the socket has several instances of the same filter * attached the 'ZMQ_UNSUBSCRIBE' option shall remove only one instance, leaving the rest in * place and functional. * * @param topic */ public final void unsubscribe(byte[] topic) { base.setsockopt(zmq.ZMQ.ZMQ_UNSUBSCRIBE, topic); mayRaiseNot (ZError.ETERM); } /** * Set custom Encoder * @param cls */ public final void setEncoder(Class<? extends EncoderBase> cls) { base.setsockopt(zmq.ZMQ.ZMQ_ENCODER, cls); } /** * Set custom Decoder * @param cls */ public final void setDecoder(Class<? extends DecoderBase> cls) { base.setsockopt(zmq.ZMQ.ZMQ_DECODER, cls); } /** * Sets the ROUTER socket behavior when an unroutable message is encountered. * * @param mandatory A value of false is the default and discards the message silently when it cannot be routed. * A value of true returns an EHOSTUNREACH error code if the message cannot be routed. */ public final void setRouterMandatory (boolean mandatory) { base.setsockopt (zmq.ZMQ.ZMQ_ROUTER_MANDATORY, mandatory ? 1 : 0); mayRaiseNot (ZError.ETERM); } /** * Sets the XPUB socket behavior on new subscriptions and unsubscriptions. * * @param verbose A value of false is the default and passes only new subscription messages to upstream. * A value of true passes all subscription messages upstream. */ public final void setXpubVerbose(boolean verbose) { base.setsockopt(zmq.ZMQ.ZMQ_XPUB_VERBOSE, verbose ? 1 : 0); mayRaiseNot (ZError.ETERM); } /** * @see #setIPv4Only (boolean) * * @return the IPV4ONLY */ public final boolean getIPv4Only () { return base.getsockopt (zmq.ZMQ.ZMQ_IPV4ONLY) == 1; } /** * The 'ZMQ_IPV4ONLY' option shall set the underlying native socket type. * An IPv6 socket lets applications connect to and accept connections from both IPv4 and IPv6 hosts. * * @param v4only A value of true will use IPv4 sockets, while the value of false will use IPv6 sockets */ public void setIPv4Only (boolean v4only) { base.setsockopt (zmq.ZMQ.ZMQ_IPV4ONLY, v4only ? 1 : 0); mayRaiseNot (ZError.ETERM); } /** * @see #setTCPKeepAlive(int) * * @return the keep alive setting. */ public int getTCPKeepAlive() { return base.getsockopt(zmq.ZMQ.ZMQ_TCP_KEEPALIVE); } /** * Override SO_KEEPALIVE socket option (where supported by OS) to enable keep-alive packets for a socket * connection. Possible values are -1, 0, 1. The default value -1 will skip all overrides and do the OS default. * * @param optVal The value of 'ZMQ_TCP_KEEPALIVE' to turn TCP keepalives on (1) or off (0). */ public void setTCPKeepAlive(int optVal) { base.setsockopt(zmq.ZMQ.ZMQ_TCP_KEEPALIVE, (int)optVal); mayRaiseNot (ZError.ETERM); } /** * Bind to network interface. Start listening for new connections. * * @param addr * the endpoint to bind to. */ public final int bind (String addr) { return bind (addr, DYNFROM, DYNTO); } /** * Bind to network interface. Start listening for new connections. * * @param addr * the endpoint to bind to. * @param min * The minimum port in the range of ports to try. * @param max * The maximum port in the range of ports to try. */ private final int bind (String addr, int min, int max) { if (addr.endsWith (":*")) { int port = min; String prefix = addr.substring (0, addr.lastIndexOf (':') + 1); while (port <= max) { addr = prefix + port; // Try to bind on the next plausible port if (base.bind (addr)) return port; port++; } } else { if (base.bind(addr)) { int port = 0; try { port = Integer.parseInt ( addr.substring (addr.lastIndexOf (':') + 1)); } catch (NumberFormatException e) { } return port; } } mayRaise (); return -1; } /** * Bind to network interface to a random port. Start listening for new * connections. * * @param addr * the endpoint to bind to. */ public int bindToRandomPort (String addr) { return bind (addr + ":*", DYNFROM, DYNTO); } /** * Bind to network interface to a random port. Start listening for new * connections. * * @param addr * the endpoint to bind to. * @param min * The minimum port in the range of ports to try. * @param max * The maximum port in the range of ports to try. */ public int bindToRandomPort (String addr, int min, int max) { return bind (addr + ":*", min, max); } /** * Connect to remote application. * * @param addr * the endpoint to connect to. */ public final void connect (String addr) { base.connect (addr); mayRaise (); } /** * Disconnect to remote application. * * @param addr * the endpoint to disconnect to. */ public final boolean disconnect (String addr) { boolean ret = base.term_endpoint (addr); mayRaise (); return ret; } public final boolean send (String data) { return send (data.getBytes (), 0); } public final boolean sendMore (String data) { return send(data.getBytes (), zmq.ZMQ.ZMQ_SNDMORE); } public final boolean send (String data, int flags) { return send(data.getBytes (), flags); } public final boolean send (byte[] data) { return send(data, 0); } public final boolean sendMore (byte[] data) { return send(data, zmq.ZMQ.ZMQ_SNDMORE); } public final boolean send (byte[] data, int flags) { zmq.Msg msg = new zmq.Msg(data); if (base.send(msg, flags)) return true; mayRaise (); return false; } /** * Send a message * * @param bb ByteBuffer payload * @param flags the flags to apply to the send operation * @return the number of bytes sent, -1 on error */ public final boolean sendByteBuffer (ByteBuffer data, int flags) { zmq.Msg msg = new zmq.Msg(data); if (base.send(msg, flags)) return true; mayRaise (); return false; } /** * Receive a message. * * @return the message received, as an array of bytes; null on error. */ public final byte[] recv () { return recv (0); } /** * Receive a message. * * @param flags * the flags to apply to the receive operation. * @return the message received, as an array of bytes; null on error. */ public final byte[] recv (int flags) { zmq.Msg msg = base.recv(flags); if (msg != null) { return msg.data(); } mayRaise (); return null; } /** * Receive a message in to a specified buffer. * * @param buffer * byte[] to copy zmq message payload in to. * @param offset * offset in buffer to write data * @param len * max bytes to write to buffer. * If len is smaller than the incoming message size, * the message will be truncated. * @param flags * the flags to apply to the receive operation. * @return the number of bytes read, -1 on error */ public final int recv (byte[] buffer, int offset, int len, int flags) { zmq.Msg msg = base.recv (flags); if (msg != null) { int size = Math.min (msg.size (), len); System.arraycopy (msg.data (), 0, buffer, offset, size); return size; } mayRaise (); return -1; } /** * Receive a message into the specified ByteBuffer * * @param buffer the buffer to copy the zmq message payload into * @param flags the flags to apply to the receive operation * @return the number of bytes read, -1 on error */ public final int recvByteBuffer (ByteBuffer buffer, int flags) { zmq.Msg msg = base.recv (flags); if (msg != null) { buffer.put(msg.data()); return msg.size(); } mayRaise (); return -1; } /** * * @return the message received, as a String object; null on no message. */ public final String recvStr () { return recvStr (0); } /** * * @param flags the flags to apply to the receive operation. * @return the message received, as a String object; null on no message. */ public final String recvStr (int flags) { byte [] msg = recv(flags); if (msg != null) { return new String (msg); } return null; } public boolean monitor (String addr, int events) { return base.monitor (addr, events); } } public static class Poller { /** * These values can be ORed to specify what we want to poll for. */ public static final int POLLIN = zmq.ZMQ.ZMQ_POLLIN; public static final int POLLOUT = zmq.ZMQ.ZMQ_POLLOUT; public static final int POLLERR = zmq.ZMQ.ZMQ_POLLERR; private static final int SIZE_DEFAULT = 32; private static final int SIZE_INCREMENT = 16; private PollItem [] items; private long timeout; private int next; public Poller (int size) { this (null, size); } /** * Class constructor. * * @param context * a 0MQ context previously created. * @param size * the number of Sockets this poller will contain. */ protected Poller (Context context, int size) { items = new PollItem[size]; timeout = -1L; next = 0; } /** * Class constructor. * * @param context * a 0MQ context previously created. */ protected Poller (Context context) { this(context, SIZE_DEFAULT); } /** * Register a Socket for polling on all events. * * @param socket * the Socket we are registering. * @return the index identifying this Socket in the poll set. */ public int register (Socket socket) { return register (socket, POLLIN | POLLOUT | POLLERR); } /** * Register a Socket for polling on the specified events. * * Automatically grow the internal representation if needed. * * @param socket * the Socket we are registering. * @param events * a mask composed by XORing POLLIN, POLLOUT and POLLERR. * @return the index identifying this Socket in the poll set. */ public int register (Socket socket, int events) { return insert (new PollItem (socket, events)); } /** * Register a Socket for polling on the specified events. * * Automatically grow the internal representation if needed. * * @param channel * the Channel we are registering. * @param events * a mask composed by XORing POLLIN, POLLOUT and POLLERR. * @return the index identifying this Channel in the poll set. */ public int register (SelectableChannel channel, int events) { return insert (new PollItem (channel, events)); } /** * Register a Channel for polling on the specified events. * * Automatically grow the internal representation if needed. * * @param item * the PollItem we are registering. * @return the index identifying this Channel in the poll set. */ public int register (PollItem item) { return insert (item); } private int insert (PollItem item) { int pos = next++; if (pos == items.length) { PollItem[] nitems = new PollItem[items.length + SIZE_INCREMENT]; System.arraycopy (items, 0, nitems, 0, items.length); items = nitems; } items [pos] = item; return pos; } /** * Unregister a Socket for polling on the specified events. * * @param socket * the Socket to be unregistered */ public void unregister (Socket socket) { for (int pos = 0; pos < items.length ;pos++) { PollItem item = items[pos]; if (item.getSocket () == socket) { remove (pos); break; } } } /** * Unregister a Socket for polling on the specified events. * * @param channel * the Socket to be unregistered */ public void unregister (SelectableChannel channel) { for (int pos = 0; pos < items.length ;pos++) { PollItem item = items[pos]; if (item.getRawSocket () == channel) { remove (pos); break; } } } private void remove (int pos) { next--; if (pos != next) items [pos] = items [next]; items [next] = null; } /** * Get the PollItem associated with an index. * * @param index * the desired index. * @return the PollItem associated with that index (or null). */ public PollItem getItem (int index) { if (index < 0 || index >= this.next) return null; return this.items[index]; } /** * Get the socket associated with an index. * * @param index * the desired index. * @return the Socket associated with that index (or null). */ public Socket getSocket (int index) { if (index < 0 || index >= this.next) return null; return items[index].getSocket (); } /** * Get the current poll timeout. * * @return the current poll timeout in milliseconds. * @deprecated Timeout handling has been moved to the poll() methods. */ public long getTimeout () { return this.timeout; } /** * Set the poll timeout. * * @param timeout * the desired poll timeout in milliseconds. * @deprecated Timeout handling has been moved to the poll() methods. */ public void setTimeout (long timeout) { if (timeout < -1) return; this.timeout = timeout; } /** * Get the current poll set size. * * @return the current poll set size. */ public int getSize () { return items.length; } /** * Get the index for the next position in the poll set size. * * @return the index for the next position in the poll set size. */ public int getNext () { return this.next; } /** * Issue a poll call. If the poller's internal timeout value * has been set, use that value as timeout; otherwise, block * indefinitely. * * @return how many objects where signaled by poll (). */ public int poll () { long tout = -1L; if (this.timeout > -1L) { tout = this.timeout; } return poll(tout); } /** * Issue a poll call, using the specified timeout value. * <p> * Since ZeroMQ 3.0, the timeout parameter is in <i>milliseconds<i>, * but prior to this the unit was <i>microseconds</i>. * * @param tout * the timeout, as per zmq_poll (); * if -1, it will block indefinitely until an event * happens; if 0, it will return immediately; * otherwise, it will wait for at most that many * milliseconds/microseconds (see above). * * @see "http://api.zeromq.org/3-0:zmq-poll" * * @return how many objects where signaled by poll () */ public int poll(long tout) { zmq.PollItem[] pollItems = new zmq.PollItem[next]; for (int i = 0; i < next; i++) pollItems[i] = items[i].base (); return zmq.ZMQ.zmq_poll (pollItems, next, tout); } /** * Check whether the specified element in the poll set was signaled for input. * * @param index * * @return true if the element was signaled. */ public boolean pollin (int index) { if (index < 0 || index >= this.next) return false; return items [index].isReadable(); } /** * Check whether the specified element in the poll set was signaled for output. * * @param index * * @return true if the element was signaled. */ public boolean pollout (int index) { if (index < 0 || index >= this.next) return false; return items [index].isWritable (); } /** * Check whether the specified element in the poll set was signaled for error. * * @param index * * @return true if the element was signaled. */ public boolean pollerr (int index) { if (index < 0 || index >= this.next) return false; return items [index].isError(); } } public static class PollItem { private final zmq.PollItem base; private final Socket socket; public PollItem (Socket socket, int ops) { this.socket = socket; base = new zmq.PollItem (socket.base, ops); } public PollItem (SelectableChannel channel, int ops) { base = new zmq.PollItem (channel, ops); socket = null; } protected final zmq.PollItem base() { return base; } public final SelectableChannel getRawSocket () { return base.getRawSocket (); } public final Socket getSocket() { return socket; } public final boolean isReadable() { return base.isReadable(); } public final boolean isWritable() { return base.isWritable (); } public final boolean isError () { return base.isError (); } public final int readyOps () { return base.readyOps (); } @Override public boolean equals (Object obj) { if (!(obj instanceof PollItem)) return false; PollItem target = (PollItem) obj; if (socket != null && socket == target.socket) return true; if (getRawSocket () != null && getRawSocket () == target.getRawSocket ()) return true; return false; } } public enum Error { ENOTSUP(ZError.ENOTSUP), EPROTONOSUPPORT(ZError.EPROTONOSUPPORT), ENOBUFS(ZError.ENOBUFS), ENETDOWN(ZError.ENETDOWN), EADDRINUSE(ZError.EADDRINUSE), EADDRNOTAVAIL(ZError.EADDRNOTAVAIL), ECONNREFUSED(ZError.ECONNREFUSED), EINPROGRESS(ZError.EINPROGRESS), EMTHREAD(ZError.EMTHREAD), EFSM(ZError.EFSM), ENOCOMPATPROTO(ZError.ENOCOMPATPROTO), ETERM(ZError.ETERM); private final long code; Error(long code) { this.code = code; } public long getCode() { return code; } public static Error findByCode(int code) { for (Error e : Error.class.getEnumConstants()) { if (e.getCode() == code) { return e; } } throw new IllegalArgumentException("Unknown " + Error.class.getName() + " enum code:" + code); } } @Deprecated public static boolean device (int type_, Socket frontend, Socket backend) { return zmq.ZMQ.zmq_proxy (frontend.base, backend.base, null); } /** * Starts the built-in ØMQ proxy in the current application thread. * The proxy connects a frontend socket to a backend socket. Conceptually, data flows from frontend to backend. * Depending on the socket types, replies may flow in the opposite direction. The direction is conceptual only; * the proxy is fully symmetric and there is no technical difference between frontend and backend. * * Before calling ZMQ.proxy() you must set any socket options, and connect or bind both frontend and backend sockets. * The two conventional proxy models are: * * ZMQ.proxy() runs in the current thread and returns only if/when the current context is closed. * @param frontend ZMQ.Socket * @param backend ZMQ.Socket * @param capture If the capture socket is not NULL, the proxy shall send all messages, received on both * frontend and backend, to the capture socket. The capture socket should be a * ZMQ_PUB, ZMQ_DEALER, ZMQ_PUSH, or ZMQ_PAIR socket. */ public static boolean proxy (Socket frontend, Socket backend, Socket capture) { return zmq.ZMQ.zmq_proxy (frontend.base, backend.base, capture != null ? capture.base: null); } public static int poll(PollItem[] items, long timeout) { return poll(items, items.length, timeout); } public static int poll(PollItem[] items, int count, long timeout) { zmq.PollItem[] items_ = new zmq.PollItem[count]; for (int i = 0; i < count; i++) { items_[i] = items[i].base; } return zmq.ZMQ.zmq_poll(items_, count, timeout); } /** * @return Major version number of the ZMQ library. */ public static int getMajorVersion () { return zmq.ZMQ.ZMQ_VERSION_MAJOR; } /** * @return Major version number of the ZMQ library. */ public static int getMinorVersion () { return zmq.ZMQ.ZMQ_VERSION_MINOR; } /** * @return Major version number of the ZMQ library. */ public static int getPatchVersion () { return zmq.ZMQ.ZMQ_VERSION_PATCH; } /** * @return Full version number of the ZMQ library used for comparing versions. */ public static int getFullVersion() { return zmq.ZMQ.ZMQ_MAKE_VERSION(zmq.ZMQ.ZMQ_VERSION_MAJOR, zmq.ZMQ.ZMQ_VERSION_MINOR, zmq.ZMQ.ZMQ_VERSION_PATCH); } /** * @param major Version major component. * @param minor Version minor component. * @param patch Version patch component. * * @return Comparible single int version number. */ public static int makeVersion ( final int major, final int minor, final int patch ) { return zmq.ZMQ.ZMQ_MAKE_VERSION ( major, minor, patch ); } /** * @return String version number in the form major.minor.patch. */ public static String getVersionString() { return "" + zmq.ZMQ.ZMQ_VERSION_MAJOR + "." + zmq.ZMQ.ZMQ_VERSION_MINOR + "." + zmq.ZMQ.ZMQ_VERSION_PATCH; } }
expose special purpose raw zmq.SocketBase
src/main/java/org/zeromq/ZMQ.java
expose special purpose raw zmq.SocketBase
<ide><path>rc/main/java/org/zeromq/ZMQ.java <ide> base = base_; <ide> } <ide> <del> protected SocketBase base() { <add> /** <add> * DO NOT USE if you're trying to build a special proxy <add> * <add> * @return raw zmq.SocketBase <add> */ <add> public SocketBase base() { <ide> return base; <ide> } <ide>
JavaScript
mit
4c12e8a725267e60b6eda4e7ffcb25bba7de2f5f
0
bergie/VIE,bergie/VIE
module("vie.js - RDFa Service"); test("Test simple RDFa parsing", function() { var z = new VIE(); z.use(new z.RdfaService); var html = jQuery('<div xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:dbp="http://dbpedia.org/property/" about="http://dbpedia.org/resource/Albert_Einstein"><span property="foaf:name">Albert Einstein</span><span property="dbp:dateOfBirth" datatype="xsd:date">1879-03-14</span><div rel="dbp:birthPlace" resource="http://dbpedia.org/resource/Germany" /><span about="http://dbpedia.org/resource/Germany" property="dbp:conventionalLongName">Federal Republic of Germany</span></div>'); stop(1000); // 1 second timeout z.load({element: html}).from('rdfa').execute().done(function(entities) { ok(entities); equal(entities.length, 2); equal(entities[1].id, '<http://dbpedia.org/resource/Albert_Einstein>'); equal(entities[1].get('foaf:name'), 'Albert Einstein'); equal(entities[0].get('dbp:conventionalLongName'), 'Federal Republic of Germany'); equal(z.entities.get('<http://dbpedia.org/resource/Germany>').id, entities[0].id); start(); }); }); test("Test updating RDFa views", function() { var z = new VIE(); z.use(new z.RdfaService); var html = jQuery('<div xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:dbp="http://dbpedia.org/property/" about="http://dbpedia.org/resource/Albert_Einstein"><span property="foaf:name">Albert Einstein</span><span property="dbp:dateOfBirth" datatype="xsd:date">1879-03-14</span><div rel="dbp:birthPlace" resource="http://dbpedia.org/resource/Germany" /><span about="http://dbpedia.org/resource/Germany" property="dbp:conventionalLongName">Federal Republic of Germany</span></div>'); stop(1000); // 1 second timeout z.load({element: html}).from('rdfa').execute().done(function(entities) { ok(entities); equal(entities.length, 2); equal(entities[0].get('dbp:conventionalLongName'), 'Federal Republic of Germany'); entities[0].set({'dbp:conventionalLongName': 'Switzerland'}); equal(entities[0].get('dbp:conventionalLongName'), 'Switzerland'); jQuery('[property="dbp:conventionalLongName"]', html).each(function() { equal(jQuery(this).html(), 'Switzerland'); }); start(); }); }); test("Test simple RDFa nested tags", function() { var z = new VIE(); z.use(new z.RdfaService); var html = jQuery('<div xmlns:dcterms="http://purl.org/dc/terms/" id="myarticle" typeof="http://rdfs.org/sioc/ns#Post" about="http://example.net/blog/news_item"><h1 property="dcterms:title"><span>News item title</span></h1></div>'); stop(1000); // 1 second timeout z.load({element: html}).from('rdfa').execute().done(function(entities) { equal(entities.length, 1); equal(entities[0].get('dcterms:title').toUpperCase(), '<span>News item title</span>'.toUpperCase()); start(); }); }); test("Test RDFa property content", function() { var z = new VIE(); z.use(new z.RdfaService); var html = jQuery('<div xmlns:iks="http://iks-project.eu/ontology/" xmlns:foaf="http://xmlns.com/foaf/0.1/" about="http://twitter.com/bergie"><span property="foaf:name">Henri Bergius</span><span property="iks:online" content="0"></span></div>'); stop(1000); // 1 second timeout z.load({element: html}).from('rdfa').execute().done(function(entities) { equal(entities.length, 1); equal(entities[0].get('iks:online'), 0); entities[0].set({'iks:online': 1}); equal(entities[0].get('iks:online'), 1); equal(jQuery('[property="iks:online"]', html).attr('content'), 1); equal(jQuery('[property="iks:online"]', html).text(), ''); start(); }); }); test("Test RDFa example from Wikipedia", function() { var z = new VIE(); z.use(new z.RdfaService); var html = jQuery('<p xmlns:dc="http://purl.org/dc/elements/1.1/" about="http://www.example.com/books/wikinomics">In his latest book <cite property="dc:title">Wikinomics</cite>, <span property="dc:creator">Don Tapscott</span> explains deep changes in technology, demographics and business. The book is due to be published in <span property="dc:date" content="2006-10-01">October 2006</span>.</p>'); stop(1000); // 1 second timeout z.load({element: html}).from('rdfa').execute().done(function(entities) { var objectInstance = z.entities.get('<http://www.example.com/books/wikinomics>'); equal(objectInstance.get('dc:title'), 'Wikinomics'); equal(objectInstance.get('dc:creator'), 'Don Tapscott'); start(); }); }); test("Test RDFa image entitization", function() { var z = new VIE(); z.namespaces.add('mgd', 'http://midgard-project.org/ontology/'); z.namespaces.add('dcterms', 'http://purl.org/dc/terms/'); z.use(new z.RdfaService); var html = jQuery('<div id="myarticle" typeof="http://rdfs.org/sioc/ns#Post" about="http://example.net/blog/news_item"><h1 property="dcterms:title"><span>News item title</span></h1><span rel="mgd:icon"><img typeof="mgd:photo" src="http://example.net/image.jpg" /></span></div>'); stop(1000); // 1 second timeout z.load({element: html}).from('rdfa').execute().done(function(entities) { var icons = z.entities.get('<http://example.net/blog/news_item>').get('mgd:icon'); // Ensure we have the image correctly read ok(icons instanceof z.Collection, "Icons should be a collection"); equal(icons.at(0).id, '<http://example.net/image.jpg>'); equal(jQuery('img', html).length, 1); // Remove it and replace with another image icons.remove(icons.at(0)); equal(jQuery('img', html).length, 0); icons.add({'@subject': '<http://example.net/otherimage.jpg>'}); equal(jQuery('img', html).length, 1); equal(jQuery('img[src="http://example.net/otherimage.jpg"]', html).length, 1); start(); }); });
test/service/rdfa.js
module("vie.js - RDFa Service"); test("Test simple RDFa parsing", function() { var z = new VIE(); z.use(new z.RdfaService); var html = jQuery('<div xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:dbp="http://dbpedia.org/property/" about="http://dbpedia.org/resource/Albert_Einstein"><span property="foaf:name">Albert Einstein</span><span property="dbp:dateOfBirth" datatype="xsd:date">1879-03-14</span><div rel="dbp:birthPlace" resource="http://dbpedia.org/resource/Germany" /><span about="http://dbpedia.org/resource/Germany" property="dbp:conventionalLongName">Federal Republic of Germany</span></div>'); stop(1000); // 1 second timeout z.load({element: html}).from('rdfa').execute().done(function(entities) { ok(entities); equal(entities.length, 2); equal(entities[1].id, '<http://dbpedia.org/resource/Albert_Einstein>'); equal(entities[1].get('foaf:name'), 'Albert Einstein'); equal(entities[0].get('dbp:conventionalLongName'), 'Federal Republic of Germany'); equal(z.entities.get('<http://dbpedia.org/resource/Germany>').id, entities[0].id); start(); }); }); test("Test updating RDFa views", function() { var z = new VIE(); z.use(new z.RdfaService); var html = jQuery('<div xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:dbp="http://dbpedia.org/property/" about="http://dbpedia.org/resource/Albert_Einstein"><span property="foaf:name">Albert Einstein</span><span property="dbp:dateOfBirth" datatype="xsd:date">1879-03-14</span><div rel="dbp:birthPlace" resource="http://dbpedia.org/resource/Germany" /><span about="http://dbpedia.org/resource/Germany" property="dbp:conventionalLongName">Federal Republic of Germany</span></div>'); stop(1000); // 1 second timeout z.load({element: html}).from('rdfa').execute().done(function(entities) { ok(entities); equal(entities.length, 2); equal(entities[0].get('dbp:conventionalLongName'), 'Federal Republic of Germany'); entities[0].set({'dbp:conventionalLongName': 'Switzerland'}); equal(entities[0].get('dbp:conventionalLongName'), 'Switzerland'); jQuery('[property="dbp:conventionalLongName"]', html).each(function() { equal(jQuery(this).html(), 'Switzerland'); }); start(); }); }); test("Test simple RDFa nested tags", function() { var z = new VIE(); z.use(new z.RdfaService); var html = jQuery('<div xmlns:dcterms="http://purl.org/dc/terms/" id="myarticle" typeof="http://rdfs.org/sioc/ns#Post" about="http://example.net/blog/news_item"><h1 property="dcterms:title"><span>News item title</span></h1></div>'); stop(1000); // 1 second timeout z.load({element: html}).from('rdfa').execute().done(function(entities) { equal(entities.length, 1); equal(entities[0].get('dcterms:title').toUpperCase(), '<span>News item title</span>'.toUpperCase()); start(); }); }); test("Test RDFa property content", function() { var z = new VIE(); z.use(new z.RdfaService); var html = jQuery('<div xmlns:iks="http://iks-project.eu/ontology/" xmlns:foaf="http://xmlns.com/foaf/0.1/" about="http://twitter.com/bergie"><span property="foaf:name">Henri Bergius</span><span property="iks:online" content="0"></span></div>'); stop(1000); // 1 second timeout z.load({element: html}).from('rdfa').execute().done(function(entities) { equal(entities.length, 1); equal(entities[0].get('iks:online'), 0); entities[0].set({'iks:online': 1}); equal(entities[0].get('iks:online'), 1); equal(jQuery('[property="iks:online"]', html).attr('content'), 1); equal(jQuery('[property="iks:online"]', html).text(), ''); start(); }); }); test("Test RDFa example from Wikipedia", function() { var z = new VIE(); z.use(new z.RdfaService); var html = jQuery('<p xmlns:dc="http://purl.org/dc/elements/1.1/" about="http://www.example.com/books/wikinomics">In his latest book <cite property="dc:title">Wikinomics</cite>, <span property="dc:creator">Don Tapscott</span> explains deep changes in technology, demographics and business. The book is due to be published in <span property="dc:date" content="2006-10-01">October 2006</span>.</p>'); stop(1000); // 1 second timeout z.load({element: html}).from('rdfa').execute().done(function(entities) { var objectInstance = z.entities.get('<http://www.example.com/books/wikinomics>'); equal(objectInstance.get('dc:title'), 'Wikinomics'); equal(objectInstance.get('dc:creator'), 'Don Tapscott'); start(); }); }); test("Test RDFa image entitization", function() { var z = new VIE(); z.namespaces.add('mgd', 'http://midgard-project.org/ontology/'); z.namespaces.add('dcterms', 'http://purl.org/dc/terms/'); z.use(new z.RdfaService); var html = jQuery('<div id="myarticle" typeof="http://rdfs.org/sioc/ns#Post" about="http://example.net/blog/news_item"><h1 property="dcterms:title"><span>News item title</span></h1><span rel="mgd:icon"><img typeof="mgd:photo" src="http://example.net/image.jpg" /></span></div>'); stop(1000); // 1 second timeout z.load({element: html}).from('rdfa').execute().done(function(entities) { var icons = z.entities.get('<http://example.net/blog/news_item>').get('mgd:icon'); // Ensure we have the image correctly read ok(icons instanceof z.Collection, "Icons should be a collection"); equal(icons.at(0).id, '<http://example.net/image.jpg>'); equal(jQuery('img', html).length, 1); z.entities.get('<http://example.net/blog/news_item>').unset("mgd:icon"); equal(jQuery('img', html).length, 1); icons.add({'@subject': '<http://example.net/otherimage.jpg>'}); z.entities.get('<http://example.net/blog/news_item>').set({ "mgd:icon" : icons }); equal(jQuery('img', html).length, 0); equal(jQuery('img[src="http://example.net/otherimage.jpg"]', html).length, 0); start(); }); });
Make the image test less silly
test/service/rdfa.js
Make the image test less silly
<ide><path>est/service/rdfa.js <ide> <ide> equal(jQuery('img', html).length, 1); <ide> <del> z.entities.get('<http://example.net/blog/news_item>').unset("mgd:icon"); <add> // Remove it and replace with another image <add> icons.remove(icons.at(0)); <add> equal(jQuery('img', html).length, 0); <add> <add> icons.add({'@subject': '<http://example.net/otherimage.jpg>'}); <ide> <ide> equal(jQuery('img', html).length, 1); <del> <del> icons.add({'@subject': '<http://example.net/otherimage.jpg>'}); <del> z.entities.get('<http://example.net/blog/news_item>').set({ <del> "mgd:icon" : icons <del> }); <del> <del> equal(jQuery('img', html).length, 0); <del> <del> equal(jQuery('img[src="http://example.net/otherimage.jpg"]', html).length, 0); <add> equal(jQuery('img[src="http://example.net/otherimage.jpg"]', html).length, 1); <ide> <ide> start(); <ide> });
JavaScript
mit
10196f62a31c5c11385ece6f096794f22df11728
0
CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder
'use strict'; var plugins = require('../../plugins'); var config = require('../config'); var es = require('collections-online/lib/services/elasticsearch'); var Q = require('q'); var fs = require('fs'); var path = require('path'); var Canvas = require('canvas'); var Image = Canvas.Image; const Transform = require('stream').Transform; var imageController = plugins.getFirst('image-controller'); if(!imageController) { throw new Error('Expected at least one image controller!'); } const POSSIBLE_SIZES = config.thumbnailSizes; const WATERMARK_SCALE = 0.33; // 20% of the width of the thumbnail const THUMBNAIL_SIZE = 350; // Looping through the licenses to find the on const WATERMARKED_LICENSE_IDS = config.licenseMapping .map((license, licenseId) => { return { id: licenseId, watermark: license && license.watermark }; }) .filter(license => license.watermark) .map(license => license.id); var WATERMARK_BUFFERS = {}; Object.keys(config.watermarks || {}).forEach((catalog) => { var path = config.watermarks[catalog]; WATERMARK_BUFFERS[catalog] = fs.readFileSync(path); }); var FALLBACK_PATH = path.normalize(config.appDir + '/images/fallback.png'); const contentDispositionRegexp = /.*\.([^.]+)$/i; exports.download = function(req, res, next) { var collection = req.params.collection; var id = req.params.id; var size = req.params.size; if (size && POSSIBLE_SIZES.indexOf(size) === -1) { throw new Error('The size is required and must be one of ' + POSSIBLE_SIZES + ' given: "' + size + '"'); } var proxyRequest = imageController.proxyDownload(collection + '/' + id, { options: size }); res._writeHead = res.writeHead; res.writeHead = function(statusCode, reasonPhrase, headers) { // Reading the file extension from the response from CIP var responseHeaders = proxyRequest.response.headers; var contentDispositionHeader = responseHeaders['content-disposition'] || ''; var extension = contentDispositionHeader.match(contentDispositionRegexp); if(extension) { extension = '.' + extension[1]; } else { extension = '.jpg'; // Default extension, when the CIP is not responsing } if(size) { // Remove JPEG from e.g. kbh-museum-26893-originalJPEG.jpg size = size.replace('JPEG', ''); size = '-' + size; } // Generating a new filename adding size if it exists var filename = collection + '-' + id + size + extension; res.header('content-disposition', 'attachment; filename=' + filename); res._writeHead(statusCode, reasonPhrase, headers); }; proxyRequest .on('error', next) .on('response', function(response) { if(response.statusCode === 200) { proxyRequest.pipe(res); } else { res.type('png'); getErrorPlaceholderStream().pipe(res); } }); }; function bottomRightPosition(img, watermarkImg) { var watermarkRatio = watermarkImg.height / watermarkImg.width; var watermarkWidth = img.width * WATERMARK_SCALE; var watermarkHeight = watermarkWidth * watermarkRatio; return { left: img.width - watermarkWidth, top: img.height - watermarkHeight, width: watermarkWidth, height: watermarkHeight }; } function middleCenterPosition(img, watermarkImg) { var watermarkRatio = watermarkImg.height / watermarkImg.width; var watermarkWidth = img.width * WATERMARK_SCALE; var watermarkHeight = watermarkWidth * watermarkRatio; return { left: img.width/2 - watermarkWidth / 2, top: img.height/2 - watermarkHeight / 2, width: watermarkWidth, height: watermarkHeight }; } const POSITION_FUNCTIONS = { 'middle-center': middleCenterPosition, 'bottom-right': bottomRightPosition }; function watermarkTransformation(watermarkBuffer, maxSize, positionFunction) { var imageData = []; return new Transform({ transform(chunk, encoding, callback) { imageData.push(chunk); callback(); }, flush: function(callback) { var img = new Image; img.src = Buffer.concat(imageData); // Cap the maxSize at the largest of the width and height to avoid // stretching beyound the original image maxSize = Math.min(maxSize, Math.max(img.width, img.height)); var ratio = img.width / img.height; var newSize = { width: ratio >= 1 ? maxSize : maxSize * ratio, height: ratio < 1 ? maxSize : maxSize / ratio, }; var canvas = new Canvas(newSize.width, newSize.height); var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, newSize.width, newSize.height); // If both a watermark buffer and position is defined, we can draw it if(watermarkBuffer && positionFunction) { var watermarkImg = new Image; watermarkImg.src = watermarkBuffer; var position = positionFunction(newSize, watermarkImg); // Draw the watermark in the ctx.drawImage(watermarkImg, position.left, position.top, position.width, position.height); } // Size of the jpeg stream is just ~ 15% of the raw PNG buffer canvas.jpegStream() .on('data', (chuck) => { this.push(chuck); }) .on('end', () => { callback(); }); } }); } function getErrorPlaceholderStream() { return fs.createReadStream(FALLBACK_PATH); } exports.thumbnail = function(req, res, next) { var collection = req.params.collection; var id = req.params.id; var size = req.params.size ? parseInt(req.params.size, 10) : THUMBNAIL_SIZE; var position = req.params.position || 'middle-center'; if(!(position in POSITION_FUNCTIONS)) { throw new Error('Unexpected position function: ' + position); } // Let's find out what the license on the asset is es.getSource({ index: config.es.assetsIndex, type: 'asset', id: collection + '-' + id // TODO: Change '-' to '/asset/' }) .then(function(metadata) { var proxyRequest = imageController.proxyThumbnail(collection + '/' + id, next); // Apply the watermark if the config's licenseMapping states it var doWatermark = !metadata.license || WATERMARKED_LICENSE_IDS.indexOf(metadata.license.id) > -1; // We should only apply the watermark when the size is large doWatermark = doWatermark && size > THUMBNAIL_SIZE && config.features.watermarks; var watermark = null; var positionFunction = null; if (doWatermark && collection in WATERMARK_BUFFERS) { watermark = WATERMARK_BUFFERS[collection]; positionFunction = POSITION_FUNCTIONS[position]; } var transformation = watermarkTransformation(watermark, size, positionFunction); proxyRequest .on('error', next) .on('response', function(response) { if(response.statusCode === 200) { proxyRequest.pipe(transformation).pipe(res); } else { res.type('png'); getErrorPlaceholderStream().pipe(res); } }); }).then(null, next); };
lib/controllers/images.js
'use strict'; var plugins = require('../../plugins'); var config = require('../config'); var es = require('collections-online/lib/services/elasticsearch'); var Q = require('q'); var fs = require('fs'); var path = require('path'); var Canvas = require('canvas'); var Image = Canvas.Image; const Transform = require('stream').Transform; var imageController = plugins.getFirst('image-controller'); if(!imageController) { throw new Error('Expected at least one image controller!'); } const POSSIBLE_SIZES = ['lille', 'mellem', 'stor', 'originalJPEG', 'original']; const WATERMARK_SCALE = 0.33; // 20% of the width of the thumbnail const THUMBNAIL_SIZE = 350; // Looping through the licenses to find the on const WATERMARKED_LICENSE_IDS = config.licenseMapping .map((license, licenseId) => { return { id: licenseId, watermark: license.watermark }; }) .filter(license => license.watermark) .map(license => license.id); // Resolving the watermark path relative to the app dir's images dir var watermarkPath = path.normalize(config.appDir + '/images/watermarks'); const WATERMARK_BUFFERS = { 'kbh-museum': fs.readFileSync(watermarkPath + '/kbh-museum.png'), 'kbh-arkiv': fs.readFileSync(watermarkPath + '/kbh-arkiv.png'), }; var FALLBACK_PATH = path.normalize(config.appDir + '/images/fallback.png'); const contentDispositionRegexp = /.*\.([^.]+)$/i; exports.download = function(req, res, next) { var collection = req.params.collection; var id = req.params.id; var size = req.params.size; if (size && POSSIBLE_SIZES.indexOf(size) === -1) { throw new Error('The size is required and must be one of ' + POSSIBLE_SIZES + ' given: "' + size + '"'); } var proxyRequest = imageController.proxyDownload(collection + '/' + id, { options: size }); res._writeHead = res.writeHead; res.writeHead = function(statusCode, reasonPhrase, headers) { // Reading the file extension from the response from CIP var responseHeaders = proxyRequest.response.headers; var contentDispositionHeader = responseHeaders['content-disposition'] || ''; var extension = contentDispositionHeader.match(contentDispositionRegexp); if(extension) { extension = '.' + extension[1]; } else { extension = '.jpg'; // Default extension, when the CIP is not responsing } if(size) { // Remove JPEG from e.g. kbh-museum-26893-originalJPEG.jpg size = size.replace('JPEG', ''); size = '-' + size; } // Generating a new filename adding size if it exists var filename = collection + '-' + id + size + extension; res.header('content-disposition', 'attachment; filename=' + filename); res._writeHead(statusCode, reasonPhrase, headers); }; proxyRequest .on('error', next) .on('response', function(response) { if(response.statusCode === 200) { proxyRequest.pipe(res); } else { res.type('png'); getErrorPlaceholderStream().pipe(res); } }); }; function bottomRightPosition(img, watermarkImg) { var watermarkRatio = watermarkImg.height / watermarkImg.width; var watermarkWidth = img.width * WATERMARK_SCALE; var watermarkHeight = watermarkWidth * watermarkRatio; return { left: img.width - watermarkWidth, top: img.height - watermarkHeight, width: watermarkWidth, height: watermarkHeight }; } function middleCenterPosition(img, watermarkImg) { var watermarkRatio = watermarkImg.height / watermarkImg.width; var watermarkWidth = img.width * WATERMARK_SCALE; var watermarkHeight = watermarkWidth * watermarkRatio; return { left: img.width/2 - watermarkWidth / 2, top: img.height/2 - watermarkHeight / 2, width: watermarkWidth, height: watermarkHeight }; } const POSITION_FUNCTIONS = { 'middle-center': middleCenterPosition, 'bottom-right': bottomRightPosition }; function watermarkTransformation(watermarkBuffer, maxSize, positionFunction) { var imageData = []; return new Transform({ transform(chunk, encoding, callback) { imageData.push(chunk); callback(); }, flush: function(callback) { var img = new Image; img.src = Buffer.concat(imageData); // Cap the maxSize at the largest of the width and height to avoid // stretching beyound the original image maxSize = Math.min(maxSize, Math.max(img.width, img.height)); var ratio = img.width / img.height; var newSize = { width: ratio >= 1 ? maxSize : maxSize * ratio, height: ratio < 1 ? maxSize : maxSize / ratio, }; var canvas = new Canvas(newSize.width, newSize.height); var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, newSize.width, newSize.height); // If both a watermark buffer and position is defined, we can draw it if(watermarkBuffer && positionFunction) { var watermarkImg = new Image; watermarkImg.src = watermarkBuffer; var position = positionFunction(newSize, watermarkImg); // Draw the watermark in the ctx.drawImage(watermarkImg, position.left, position.top, position.width, position.height); } // Size of the jpeg stream is just ~ 15% of the raw PNG buffer canvas.jpegStream() .on('data', (chuck) => { this.push(chuck); }) .on('end', () => { callback(); }); } }); } function getErrorPlaceholderStream() { return fs.createReadStream(FALLBACK_PATH); } exports.thumbnail = function(req, res, next) { var collection = req.params.collection; var id = req.params.id; var size = req.params.size ? parseInt(req.params.size, 10) : THUMBNAIL_SIZE; var position = req.params.position || 'middle-center'; if(!(position in POSITION_FUNCTIONS)) { throw new Error('Unexpected position function: ' + position); } // Let's find out what the license on the asset is es.getSource({ index: config.es.assetsIndex, type: 'asset', id: collection + '-' + id // TODO: Change '-' to '/asset/' }) .then(function(metadata) { var proxyRequest = imageController.proxyThumbnail(collection + '/' + id, next); // Apply the watermark if the config's licenseMapping states it var doWatermark = !metadata.license || WATERMARKED_LICENSE_IDS.indexOf(metadata.license.id) > -1; // We should only apply the watermark when the size is large doWatermark = doWatermark && size > THUMBNAIL_SIZE; var watermark = null; var positionFunction = null; if (doWatermark && collection in WATERMARK_BUFFERS) { watermark = WATERMARK_BUFFERS[collection]; positionFunction = POSITION_FUNCTIONS[position]; } var transformation = watermarkTransformation(watermark, size, positionFunction); proxyRequest .on('error', next) .on('response', function(response) { if(response.statusCode === 200) { proxyRequest.pipe(transformation).pipe(res); } else { res.type('png'); getErrorPlaceholderStream().pipe(res); } }); }).then(null, next); };
Moved watermark paths to the configuration
lib/controllers/images.js
Moved watermark paths to the configuration
<ide><path>ib/controllers/images.js <ide> throw new Error('Expected at least one image controller!'); <ide> } <ide> <del>const POSSIBLE_SIZES = ['lille', 'mellem', 'stor', 'originalJPEG', 'original']; <add>const POSSIBLE_SIZES = config.thumbnailSizes; <ide> const WATERMARK_SCALE = 0.33; // 20% of the width of the thumbnail <ide> const THUMBNAIL_SIZE = 350; <ide> <ide> .map((license, licenseId) => { <ide> return { <ide> id: licenseId, <del> watermark: license.watermark <add> watermark: license && license.watermark <ide> }; <ide> }) <ide> .filter(license => license.watermark) <ide> .map(license => license.id); <ide> <del>// Resolving the watermark path relative to the app dir's images dir <del>var watermarkPath = path.normalize(config.appDir + '/images/watermarks'); <del>const WATERMARK_BUFFERS = { <del> 'kbh-museum': fs.readFileSync(watermarkPath + '/kbh-museum.png'), <del> 'kbh-arkiv': fs.readFileSync(watermarkPath + '/kbh-arkiv.png'), <del>}; <add>var WATERMARK_BUFFERS = {}; <add>Object.keys(config.watermarks || {}).forEach((catalog) => { <add> var path = config.watermarks[catalog]; <add> WATERMARK_BUFFERS[catalog] = fs.readFileSync(path); <add>}); <ide> <ide> var FALLBACK_PATH = path.normalize(config.appDir + '/images/fallback.png'); <ide> <ide> var doWatermark = !metadata.license || <ide> WATERMARKED_LICENSE_IDS.indexOf(metadata.license.id) > -1; <ide> // We should only apply the watermark when the size is large <del> doWatermark = doWatermark && size > THUMBNAIL_SIZE; <add> doWatermark = doWatermark && <add> size > THUMBNAIL_SIZE && <add> config.features.watermarks; <ide> var watermark = null; <ide> var positionFunction = null; <ide> if (doWatermark && collection in WATERMARK_BUFFERS) {
Java
apache-2.0
1b04280a1bc248e61531653278afea31d9576fdb
0
FabioFiuza/buendia,luisfdeandrade/buendia,pedromarins/buendia,christianrafael/buendia,christianrafael/buendia,luisfdeandrade/buendia,TeixeiraRafael/buendia,pedromarins/buendia,FabioFiuza/buendia,jozadaquebatista/buendia,danilogit/buendia,jozadaquebatista/buendia,viniciusboson/buendia,danilogit/buendia,luisfdeandrade/buendia,jozadaquebatista/buendia,G1DR4/buendia,G1DR4/buendia,pedromarins/buendia,projectbuendia/buendia,llvasconcellos/buendia,christianrafael/buendia,jozadaquebatista/buendia,TeixeiraRafael/buendia,projectbuendia/buendia,G1DR4/buendia,viniciusboson/buendia,llvasconcellos/buendia,danilogit/buendia,luisfdeandrade/buendia,christianrafael/buendia,jozadaquebatista/buendia,G1DR4/buendia,danilogit/buendia,viniciusboson/buendia,viniciusboson/buendia,projectbuendia/buendia,fcruz/buendia,fcruz/buendia,felipsimoes/buendia,FabioFiuza/buendia,viniciusboson/buendia,TeixeiraRafael/buendia,projectbuendia/buendia,llvasconcellos/buendia,christianrafael/buendia,G1DR4/buendia,FabioFiuza/buendia,felipsimoes/buendia,llvasconcellos/buendia,danilogit/buendia,projectbuendia/buendia,fcruz/buendia,felipsimoes/buendia,llvasconcellos/buendia,felipsimoes/buendia,pedromarins/buendia,fcruz/buendia,viniciusboson/buendia,felipsimoes/buendia,TeixeiraRafael/buendia,christianrafael/buendia,fcruz/buendia,luisfdeandrade/buendia,pedromarins/buendia,jozadaquebatista/buendia,TeixeiraRafael/buendia,llvasconcellos/buendia,FabioFiuza/buendia,danilogit/buendia,felipsimoes/buendia,pedromarins/buendia,luisfdeandrade/buendia,fcruz/buendia,TeixeiraRafael/buendia,FabioFiuza/buendia,G1DR4/buendia
package org.openmrs.projectbuendia.webservices.rest; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.*; import org.openmrs.api.*; import org.openmrs.api.context.Context; import org.openmrs.module.webservices.rest.SimpleObject; import org.openmrs.module.webservices.rest.web.RequestContext; import org.openmrs.module.webservices.rest.web.RestConstants; import org.openmrs.module.webservices.rest.web.annotation.Resource; import org.openmrs.module.webservices.rest.web.representation.Representation; import org.openmrs.module.webservices.rest.web.resource.api.*; import org.openmrs.module.webservices.rest.web.response.ObjectNotFoundException; import org.openmrs.module.webservices.rest.web.response.ResponseException; import org.projectbuendia.openmrs.webservices.rest.RestController; import java.util.*; /** * Resource for users (note that users are stored as Providers, Persons, and Users, but only * Providers will be returned by List calls). * * Expected behavior: * GET /user returns "full_name" and "user_id" fields, * as well as "given_name" and "family_name" if present. * GET /user/[UUID] returns information on a single user * GET /user?q=[QUERY] performs a substring search on user full names * POST /user creates a new user. This requires a "user_name", "given_name", and "password", * as well as an optional "family_name". Passwords must be >8 characters, contain at * least one number, and contain at least one uppercase character. * * Note: this is under org.openmrs as otherwise the resource annotation isn't picked up. */ @Resource(name = RestController.REST_VERSION_1_AND_NAMESPACE + "/user", supportedClass = Provider.class, supportedOpenmrsVersions = "1.10.*,1.11.*") public class UserResource implements Listable, Searchable, Retrievable, Creatable { // JSON property names private static final String USER_ID = "user_id"; private static final String USER_NAME = "user_name"; private static final String FULL_NAME = "full_name"; // Ignored on create. private static final String FAMILY_NAME = "family_name"; private static final String GIVEN_NAME = "given_name"; private static final String PASSWORD = "password"; // Sentinel for unknown values private static final String UNKNOWN = "(UNKNOWN)"; // Defaults for guest account private static final String GUEST_FULL_NAME = "Guest User"; private static final String GUEST_GIVEN_NAME = "Guest"; private static final String GUEST_FAMILY_NAME = "User"; private static final String GUEST_USER_NAME = "guest"; private static final String GUEST_PASSWORD = "Password123"; private static final String[] REQUIRED_FIELDS = {USER_NAME, GIVEN_NAME, PASSWORD}; private static Log log = LogFactory.getLog(UserResource.class); static final RequestLogger logger = RequestLogger.LOGGER; private final PersonService personService; private final ProviderService providerService; private final UserService userService; public UserResource() { personService = Context.getPersonService(); providerService = Context.getProviderService(); userService = Context.getUserService(); } @Override public SimpleObject getAll(RequestContext context) throws ResponseException { try { logger.request(context, this, "getAll"); SimpleObject result = getAllInner(context); logger.reply(context, this, "getAll", result); return result; } catch (Exception e) { logger.error(context, this, "getAll", e); throw e; } } private SimpleObject getAllInner(RequestContext requestContext) throws ResponseException { List<Provider> providers; // Returning providers is not a thread-safe operation as it may add the guest user // to the database, which is not idempotent. synchronized(this) { providers = providerService.getAllProviders(false); // omit retired addGuestIfNotPresent(providers); } return getSimpleObjectWithResults(providers); } private void addGuestIfNotPresent(List<Provider> providers) { boolean guestFound = false; for (Provider provider : providers) { if (provider.getName().equals(GUEST_FULL_NAME)) { guestFound = true; break; } } if (!guestFound) { SimpleObject guestDetails = new SimpleObject(); guestDetails.put(GIVEN_NAME, GUEST_GIVEN_NAME); guestDetails.put(FAMILY_NAME, GUEST_FAMILY_NAME); guestDetails.put(USER_NAME, GUEST_USER_NAME); guestDetails.put(PASSWORD, GUEST_PASSWORD); providers.add(createFromSimpleObject(guestDetails)); } } @Override public Object create(SimpleObject obj, RequestContext context) throws ResponseException { try { logger.request(context, this, "create", obj); Object result = createInner(obj, context); logger.reply(context, this, "create", result); return result; } catch (Exception e) { logger.error(context, this, "create", e); throw e; } } private Object createInner(SimpleObject simpleObject, RequestContext requestContext) throws ResponseException { return providerToJson(createFromSimpleObject(simpleObject)); } private Provider createFromSimpleObject(SimpleObject simpleObject) { checkRequiredFields(simpleObject, REQUIRED_FIELDS); // TODO(akalachman): Localize full name construction? String fullName = (String)simpleObject.get(GIVEN_NAME) + " " + (String)simpleObject.get(FAMILY_NAME); Person person = new Person(); PersonName personName = new PersonName(); personName.setGivenName((String)simpleObject.get(GIVEN_NAME)); personName.setFamilyName((String)simpleObject.get(FAMILY_NAME)); person.addName(personName); person.setGender(UNKNOWN); // This is required, even though it serves no purpose here. personService.savePerson(person); User user = new User(); user.setPerson(person); user.setName(fullName); user.setUsername((String)simpleObject.get(USER_NAME)); userService.saveUser(user, (String)simpleObject.get(PASSWORD)); Provider provider = new Provider(); provider.setPerson(person); provider.setName(fullName); providerService.saveProvider(provider); log.info("Created user " + fullName); return provider; } @Override public String getUri(Object instance) { Patient patient = (Patient) instance; Resource res = getClass().getAnnotation(Resource.class); return RestConstants.URI_PREFIX + res.name() + "/" + patient.getUuid(); } @Override public Object retrieve(String uuid, RequestContext context) throws ResponseException { try { logger.request(context, this, "retrieve", uuid); Object result = retrieveInner(uuid, context); logger.reply(context, this, "retrieve", result); return result; } catch (Exception e) { logger.error(context, this, "retrieve", e); throw e; } } private Object retrieveInner(String uuid, RequestContext requestContext) throws ResponseException { Provider provider = providerService.getProviderByUuid(uuid); if (provider == null) { throw new ObjectNotFoundException(); } return providerToJson(provider); } @Override public List<Representation> getAvailableRepresentations() { return Arrays.asList(Representation.DEFAULT); } @Override public SimpleObject search(RequestContext context) throws ResponseException { try { logger.request(context, this, "search"); SimpleObject result = searchInner(context); logger.reply(context, this, "search", result); return result; } catch (Exception e) { logger.error(context, this, "search", e); throw e; } } private SimpleObject searchInner(RequestContext requestContext) throws ResponseException { // Partial string query for searches. String query = requestContext.getParameter("q"); // Retrieve all patients and filter the list based on the query. List<Provider> filteredProviders = new ArrayList<>(); // Perform a substring search on username. for (Provider provider : providerService.getAllProviders(false)) { if (StringUtils.containsIgnoreCase(provider.getName(), query)) { filteredProviders.add(provider); } } addGuestIfNotPresent(filteredProviders); return getSimpleObjectWithResults(filteredProviders); } // Throws an exception if the given SimpleObject is missing any required fields. private void checkRequiredFields(SimpleObject simpleObject, String[] requiredFields) { List<String> missingFields = new ArrayList<String>(); for (String requiredField : requiredFields) { if (!simpleObject.containsKey(requiredField)) { missingFields.add(requiredField); } } if (!missingFields.isEmpty()) { throw new InvalidObjectDataException( "JSON object lacks required fields: " + StringUtils.join(missingFields, ",")); } } private SimpleObject getSimpleObjectWithResults(List<Provider> providers) { List<SimpleObject> jsonResults = new ArrayList<>(); for (Provider provider : providers) { jsonResults.add(providerToJson(provider)); } SimpleObject list = new SimpleObject(); list.add("results", jsonResults); return list; } private SimpleObject providerToJson(Provider provider) { SimpleObject jsonForm = new SimpleObject(); if (provider != null) { jsonForm.add(USER_ID, provider.getUuid()); jsonForm.add(FULL_NAME, provider.getName()); Person person = provider.getPerson(); if (person != null) { jsonForm.add(GIVEN_NAME, person.getGivenName()); jsonForm.add(FAMILY_NAME, person.getFamilyName()); } } return jsonForm; } }
projectbuendia.openmrs/omod/src/main/java/org/openmrs/projectbuendia/webservices/rest/UserResource.java
package org.openmrs.projectbuendia.webservices.rest; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.*; import org.openmrs.api.*; import org.openmrs.api.context.Context; import org.openmrs.module.webservices.rest.SimpleObject; import org.openmrs.module.webservices.rest.web.RequestContext; import org.openmrs.module.webservices.rest.web.RestConstants; import org.openmrs.module.webservices.rest.web.annotation.Resource; import org.openmrs.module.webservices.rest.web.representation.Representation; import org.openmrs.module.webservices.rest.web.resource.api.*; import org.openmrs.module.webservices.rest.web.response.ObjectNotFoundException; import org.openmrs.module.webservices.rest.web.response.ResponseException; import org.projectbuendia.openmrs.webservices.rest.RestController; import java.util.*; /** * Resource for users (note that users are stored as Providers, Persons, and Users, but only * Providers will be returned by List calls). * * Expected behavior: * GET /user returns "full_name" and "user_id" fields, * as well as "given_name" and "family_name" if present. * GET /user/[UUID] returns information on a single user * GET /user?q=[QUERY] performs a substring search on user full names * POST /user creates a new user. This requires a "user_name", "given_name", and "password", * as well as an optional "family_name". Passwords must be >8 characters, contain at * least one number, and contain at least one uppercase character. * * Note: this is under org.openmrs as otherwise the resource annotation isn't picked up. */ @Resource(name = RestController.REST_VERSION_1_AND_NAMESPACE + "/user", supportedClass = Provider.class, supportedOpenmrsVersions = "1.10.*,1.11.*") public class UserResource implements Listable, Searchable, Retrievable, Creatable { // JSON property names private static final String USER_ID = "user_id"; private static final String USER_NAME = "user_name"; private static final String FULL_NAME = "full_name"; // Ignored on create. private static final String FAMILY_NAME = "family_name"; private static final String GIVEN_NAME = "given_name"; private static final String PASSWORD = "password"; // Sentinel for unknown values private static final String UNKNOWN = "(UNKNOWN)"; // Defaults for guest account private static final String GUEST_FULL_NAME = "Guest User"; private static final String GUEST_GIVEN_NAME = "Guest"; private static final String GUEST_FAMILY_NAME = "User"; private static final String GUEST_USER_NAME = "guest"; private static final String GUEST_PASSWORD = "Password123"; private static final String[] REQUIRED_FIELDS = {USER_NAME, GIVEN_NAME, PASSWORD}; private static Log log = LogFactory.getLog(UserResource.class); static final RequestLogger logger = RequestLogger.LOGGER; private final PersonService personService; private final ProviderService providerService; private final UserService userService; public UserResource() { personService = Context.getPersonService(); providerService = Context.getProviderService(); userService = Context.getUserService(); } @Override public SimpleObject getAll(RequestContext context) throws ResponseException { try { logger.request(context, this, "search"); SimpleObject result = getAllInner(context); logger.reply(context, this, "search", result); return result; } catch (Exception e) { logger.error(context, this, "search", e); throw e; } } private SimpleObject getAllInner(RequestContext requestContext) throws ResponseException { List<Provider> providers; // Returning providers is not a thread-safe operation as it may add the guest user // to the database, which is not idempotent. synchronized(this) { providers = providerService.getAllProviders(false); // omit retired addGuestIfNotPresent(providers); } return getSimpleObjectWithResults(providers); } private void addGuestIfNotPresent(List<Provider> providers) { boolean guestFound = false; for (Provider provider : providers) { if (provider.getName().equals(GUEST_FULL_NAME)) { guestFound = true; break; } } if (!guestFound) { SimpleObject guestDetails = new SimpleObject(); guestDetails.put(GIVEN_NAME, GUEST_GIVEN_NAME); guestDetails.put(FAMILY_NAME, GUEST_FAMILY_NAME); guestDetails.put(USER_NAME, GUEST_USER_NAME); guestDetails.put(PASSWORD, GUEST_PASSWORD); providers.add(createFromSimpleObject(guestDetails)); } } @Override public Object create(SimpleObject obj, RequestContext context) throws ResponseException { try { logger.request(context, this, "create", obj); Object result = createInner(obj, context); logger.reply(context, this, "create", result); return result; } catch (Exception e) { logger.error(context, this, "create", e); throw e; } } private Object createInner(SimpleObject simpleObject, RequestContext requestContext) throws ResponseException { return providerToJson(createFromSimpleObject(simpleObject)); } private Provider createFromSimpleObject(SimpleObject simpleObject) { checkRequiredFields(simpleObject, REQUIRED_FIELDS); // TODO(akalachman): Localize full name construction? String fullName = (String)simpleObject.get(GIVEN_NAME) + " " + (String)simpleObject.get(FAMILY_NAME); Person person = new Person(); PersonName personName = new PersonName(); personName.setGivenName((String)simpleObject.get(GIVEN_NAME)); personName.setFamilyName((String)simpleObject.get(FAMILY_NAME)); person.addName(personName); person.setGender(UNKNOWN); // This is required, even though it serves no purpose here. personService.savePerson(person); User user = new User(); user.setPerson(person); user.setName(fullName); user.setUsername((String)simpleObject.get(USER_NAME)); userService.saveUser(user, (String)simpleObject.get(PASSWORD)); Provider provider = new Provider(); provider.setPerson(person); provider.setName(fullName); providerService.saveProvider(provider); log.info("Created user " + fullName); return provider; } @Override public String getUri(Object instance) { Patient patient = (Patient) instance; Resource res = getClass().getAnnotation(Resource.class); return RestConstants.URI_PREFIX + res.name() + "/" + patient.getUuid(); } @Override public Object retrieve(String uuid, RequestContext context) throws ResponseException { try { logger.request(context, this, "retrieve", uuid); Object result = retrieveInner(uuid, context); logger.reply(context, this, "retrieve", result); return result; } catch (Exception e) { logger.error(context, this, "retrieve", e); throw e; } } private Object retrieveInner(String uuid, RequestContext requestContext) throws ResponseException { Provider provider = providerService.getProviderByUuid(uuid); if (provider == null) { throw new ObjectNotFoundException(); } return providerToJson(provider); } @Override public List<Representation> getAvailableRepresentations() { return Arrays.asList(Representation.DEFAULT); } @Override public SimpleObject search(RequestContext context) throws ResponseException { try { logger.request(context, this, "search"); SimpleObject result = searchInner(context); logger.reply(context, this, "search", result); return result; } catch (Exception e) { logger.error(context, this, "search", e); throw e; } } private SimpleObject searchInner(RequestContext requestContext) throws ResponseException { // Partial string query for searches. String query = requestContext.getParameter("q"); // Retrieve all patients and filter the list based on the query. List<Provider> filteredProviders = new ArrayList<>(); // Perform a substring search on username. for (Provider provider : providerService.getAllProviders()) { if (StringUtils.containsIgnoreCase(provider.getName(), query)) { filteredProviders.add(provider); } } addGuestIfNotPresent(filteredProviders); return getSimpleObjectWithResults(filteredProviders); } // Throws an exception if the given SimpleObject is missing any required fields. private void checkRequiredFields(SimpleObject simpleObject, String[] requiredFields) { List<String> missingFields = new ArrayList<String>(); for (String requiredField : requiredFields) { if (!simpleObject.containsKey(requiredField)) { missingFields.add(requiredField); } } if (!missingFields.isEmpty()) { throw new InvalidObjectDataException( "JSON object lacks required fields: " + StringUtils.join(missingFields, ",")); } } private SimpleObject getSimpleObjectWithResults(List<Provider> providers) { List<SimpleObject> jsonResults = new ArrayList<>(); for (Provider provider : providers) { jsonResults.add(providerToJson(provider)); } SimpleObject list = new SimpleObject(); list.add("results", jsonResults); return list; } private SimpleObject providerToJson(Provider provider) { SimpleObject jsonForm = new SimpleObject(); if (provider != null) { jsonForm.add(USER_ID, provider.getUuid()); jsonForm.add(FULL_NAME, provider.getName()); Person person = provider.getPerson(); if (person != null) { jsonForm.add(GIVEN_NAME, person.getGivenName()); jsonForm.add(FAMILY_NAME, person.getFamilyName()); } } return jsonForm; } }
Don't return retired providers; fix logging.
projectbuendia.openmrs/omod/src/main/java/org/openmrs/projectbuendia/webservices/rest/UserResource.java
Don't return retired providers; fix logging.
<ide><path>rojectbuendia.openmrs/omod/src/main/java/org/openmrs/projectbuendia/webservices/rest/UserResource.java <ide> @Override <ide> public SimpleObject getAll(RequestContext context) throws ResponseException { <ide> try { <del> logger.request(context, this, "search"); <add> logger.request(context, this, "getAll"); <ide> SimpleObject result = getAllInner(context); <del> logger.reply(context, this, "search", result); <del> return result; <del> } catch (Exception e) { <del> logger.error(context, this, "search", e); <add> logger.reply(context, this, "getAll", result); <add> return result; <add> } catch (Exception e) { <add> logger.error(context, this, "getAll", e); <ide> throw e; <ide> } <ide> } <ide> List<Provider> filteredProviders = new ArrayList<>(); <ide> <ide> // Perform a substring search on username. <del> for (Provider provider : providerService.getAllProviders()) { <add> for (Provider provider : providerService.getAllProviders(false)) { <ide> if (StringUtils.containsIgnoreCase(provider.getName(), query)) { <ide> filteredProviders.add(provider); <ide> }
Java
apache-2.0
2cae731c650e20661c604f0e8fe97ce794fe7afc
0
calvinjia/tachyon,riversand963/alluxio,apc999/alluxio,apc999/alluxio,madanadit/alluxio,Reidddddd/mo-alluxio,PasaLab/tachyon,riversand963/alluxio,aaudiber/alluxio,uronce-cc/alluxio,uronce-cc/alluxio,riversand963/alluxio,maobaolong/alluxio,Alluxio/alluxio,ChangerYoung/alluxio,bf8086/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,EvilMcJerkface/alluxio,aaudiber/alluxio,uronce-cc/alluxio,WilliamZapata/alluxio,aaudiber/alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,Reidddddd/mo-alluxio,maboelhassan/alluxio,Reidddddd/alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,wwjiang007/alluxio,maobaolong/alluxio,Alluxio/alluxio,ChangerYoung/alluxio,ShailShah/alluxio,apc999/alluxio,jswudi/alluxio,jsimsa/alluxio,calvinjia/tachyon,Reidddddd/alluxio,Alluxio/alluxio,maboelhassan/alluxio,EvilMcJerkface/alluxio,maboelhassan/alluxio,aaudiber/alluxio,bf8086/alluxio,jsimsa/alluxio,jswudi/alluxio,jsimsa/alluxio,PasaLab/tachyon,Alluxio/alluxio,aaudiber/alluxio,Alluxio/alluxio,uronce-cc/alluxio,maboelhassan/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,jswudi/alluxio,calvinjia/tachyon,Reidddddd/mo-alluxio,maboelhassan/alluxio,maobaolong/alluxio,wwjiang007/alluxio,madanadit/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,calvinjia/tachyon,bf8086/alluxio,ShailShah/alluxio,WilliamZapata/alluxio,madanadit/alluxio,madanadit/alluxio,Reidddddd/alluxio,Reidddddd/mo-alluxio,Reidddddd/mo-alluxio,uronce-cc/alluxio,PasaLab/tachyon,maobaolong/alluxio,bf8086/alluxio,WilliamZapata/alluxio,PasaLab/tachyon,wwjiang007/alluxio,maobaolong/alluxio,jsimsa/alluxio,jswudi/alluxio,madanadit/alluxio,Reidddddd/alluxio,bf8086/alluxio,ShailShah/alluxio,bf8086/alluxio,Reidddddd/alluxio,apc999/alluxio,ChangerYoung/alluxio,Reidddddd/alluxio,ChangerYoung/alluxio,jswudi/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,wwjiang007/alluxio,PasaLab/tachyon,wwjiang007/alluxio,riversand963/alluxio,jswudi/alluxio,madanadit/alluxio,maobaolong/alluxio,PasaLab/tachyon,ShailShah/alluxio,ShailShah/alluxio,EvilMcJerkface/alluxio,Alluxio/alluxio,calvinjia/tachyon,PasaLab/tachyon,apc999/alluxio,EvilMcJerkface/alluxio,madanadit/alluxio,madanadit/alluxio,apc999/alluxio,ShailShah/alluxio,Reidddddd/mo-alluxio,wwjiang007/alluxio,maobaolong/alluxio,aaudiber/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,Alluxio/alluxio,jsimsa/alluxio,ChangerYoung/alluxio,maboelhassan/alluxio,apc999/alluxio,Alluxio/alluxio,Reidddddd/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,maobaolong/alluxio,EvilMcJerkface/alluxio,Alluxio/alluxio,riversand963/alluxio,bf8086/alluxio,calvinjia/tachyon,maboelhassan/alluxio,wwjiang007/alluxio,aaudiber/alluxio,bf8086/alluxio,uronce-cc/alluxio,jsimsa/alluxio
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.wire; import alluxio.annotation.PublicApi; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.net.HostAndPort; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.concurrent.NotThreadSafe; /** * The file block information. */ @PublicApi @NotThreadSafe public final class FileBlockInfo implements Serializable { private static final long serialVersionUID = -3313640897617385301L; private BlockInfo mBlockInfo = new BlockInfo(); private long mOffset; private ArrayList<String> mUfsLocations = new ArrayList<>(); /** * Creates a new instance of {@link FileBlockInfo}. */ public FileBlockInfo() {} /** * Creates a new instance of {@link FileBlockInfo} from a thrift representation. * * @param fileBlockInfo the thrift representation of a file block information */ protected FileBlockInfo(alluxio.thrift.FileBlockInfo fileBlockInfo) { mBlockInfo = new BlockInfo(fileBlockInfo.getBlockInfo()); mOffset = fileBlockInfo.getOffset(); if (fileBlockInfo.getUfsStringLocationsSize() != 0) { mUfsLocations = new ArrayList<>(fileBlockInfo.getUfsStringLocations()); } else if (fileBlockInfo.getUfsLocationsSize() != 0) { for (alluxio.thrift.WorkerNetAddress address : fileBlockInfo.getUfsLocations()) { mUfsLocations .add(HostAndPort.fromParts(address.getHost(), address.getDataPort()).toString()); } } } /** * @return the block info */ public BlockInfo getBlockInfo() { return mBlockInfo; } /** * @return the offset */ public long getOffset() { return mOffset; } /** * @return the UFS locations */ public List<String> getUfsLocations() { return mUfsLocations; } /** * @param blockInfo the block info to use * @return the file block information */ public FileBlockInfo setBlockInfo(BlockInfo blockInfo) { Preconditions.checkNotNull(blockInfo, "blockInfo"); mBlockInfo = blockInfo; return this; } /** * @param offset the offset to use * @return the file block information */ public FileBlockInfo setOffset(long offset) { mOffset = offset; return this; } /** * @param ufsLocations the UFS locations to use * @return the file block information */ public FileBlockInfo setUfsLocations(List<String> ufsLocations) { Preconditions.checkNotNull(ufsLocations, "ufsLocations"); mUfsLocations = new ArrayList<>(ufsLocations); return this; } /** * @return thrift representation of the file block information */ protected alluxio.thrift.FileBlockInfo toThrift() { List<alluxio.thrift.WorkerNetAddress> ufsLocations = new ArrayList<>(); for (String ufsLocation : mUfsLocations) { HostAndPort address = HostAndPort.fromString(ufsLocation); ufsLocations.add(new alluxio.thrift.WorkerNetAddress().setHost(address.getHostText()) .setDataPort(address.getPortOrDefault(-1))); } return new alluxio.thrift.FileBlockInfo(mBlockInfo.toThrift(), mOffset, ufsLocations, mUfsLocations); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FileBlockInfo)) { return false; } FileBlockInfo that = (FileBlockInfo) o; return mBlockInfo.equals(that.mBlockInfo) && mOffset == that.mOffset && mUfsLocations.equals(that.mUfsLocations); } @Override public int hashCode() { return Objects.hashCode(mBlockInfo, mOffset, mUfsLocations); } @Override public String toString() { return Objects.toStringHelper(this).add("blockInfo", mBlockInfo).add("offset", mOffset) .add("ufsLocations", mUfsLocations).toString(); } }
core/common/src/main/java/alluxio/wire/FileBlockInfo.java
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.wire; import alluxio.annotation.PublicApi; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.net.HostAndPort; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.concurrent.NotThreadSafe; /** * The file block information. */ @PublicApi @NotThreadSafe public final class FileBlockInfo implements Serializable { private static final long serialVersionUID = -3313640897617385301L; private BlockInfo mBlockInfo = new BlockInfo(); private long mOffset; private ArrayList<String> mUfsLocations = new ArrayList<>(); /** * Creates a new instance of {@link FileBlockInfo}. */ public FileBlockInfo() {} /** * Creates a new instance of {@link FileBlockInfo} from a thrift representation. * * @param fileBlockInfo the thrift representation of a file block information */ protected FileBlockInfo(alluxio.thrift.FileBlockInfo fileBlockInfo) { mBlockInfo = new BlockInfo(fileBlockInfo.getBlockInfo()); mOffset = fileBlockInfo.getOffset(); if (fileBlockInfo.getUfsStringLocationsSize() != 0) { mUfsLocations = new ArrayList<>(fileBlockInfo.getUfsStringLocations()); } else if (fileBlockInfo.getUfsLocationsSize() != 0) { for (alluxio.thrift.WorkerNetAddress address : fileBlockInfo.getUfsLocations()) { mUfsLocations .add(HostAndPort.fromParts(address.getHost(), address.getDataPort()).toString()); } } } /** * @return the block info */ public BlockInfo getBlockInfo() { return mBlockInfo; } /** * @return the offset */ public long getOffset() { return mOffset; } /** * @return the UFS locations */ public List<String> getUfsLocations() { return mUfsLocations; } /** * @param blockInfo the block info to use * @return the file block information */ public FileBlockInfo setBlockInfo(BlockInfo blockInfo) { Preconditions.checkNotNull(blockInfo); mBlockInfo = blockInfo; return this; } /** * @param offset the offset to use * @return the file block information */ public FileBlockInfo setOffset(long offset) { mOffset = offset; return this; } /** * @param ufsLocations the UFS locations to use * @return the file block information */ public FileBlockInfo setUfsLocations(List<String> ufsLocations) { Preconditions.checkNotNull(ufsLocations); mUfsLocations = new ArrayList<>(ufsLocations); return this; } /** * @return thrift representation of the file block information */ protected alluxio.thrift.FileBlockInfo toThrift() { List<alluxio.thrift.WorkerNetAddress> ufsLocations = new ArrayList<>(); for (String ufsLocation : mUfsLocations) { HostAndPort address = HostAndPort.fromString(ufsLocation); ufsLocations.add(new alluxio.thrift.WorkerNetAddress().setHost(address.getHostText()) .setDataPort(address.getPortOrDefault(-1))); } return new alluxio.thrift.FileBlockInfo(mBlockInfo.toThrift(), mOffset, ufsLocations, mUfsLocations); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FileBlockInfo)) { return false; } FileBlockInfo that = (FileBlockInfo) o; return mBlockInfo.equals(that.mBlockInfo) && mOffset == that.mOffset && mUfsLocations.equals(that.mUfsLocations); } @Override public int hashCode() { return Objects.hashCode(mBlockInfo, mOffset, mUfsLocations); } @Override public String toString() { return Objects.toStringHelper(this).add("blockInfo", mBlockInfo).add("offset", mOffset) .add("ufsLocations", mUfsLocations).toString(); } }
Specify null variable in FileBlockInfo.java precondition check
core/common/src/main/java/alluxio/wire/FileBlockInfo.java
Specify null variable in FileBlockInfo.java precondition check
<ide><path>ore/common/src/main/java/alluxio/wire/FileBlockInfo.java <ide> * @return the file block information <ide> */ <ide> public FileBlockInfo setBlockInfo(BlockInfo blockInfo) { <del> Preconditions.checkNotNull(blockInfo); <add> Preconditions.checkNotNull(blockInfo, "blockInfo"); <ide> mBlockInfo = blockInfo; <ide> return this; <ide> } <ide> * @return the file block information <ide> */ <ide> public FileBlockInfo setUfsLocations(List<String> ufsLocations) { <del> Preconditions.checkNotNull(ufsLocations); <add> Preconditions.checkNotNull(ufsLocations, "ufsLocations"); <ide> mUfsLocations = new ArrayList<>(ufsLocations); <ide> return this; <ide> }
Java
apache-2.0
6c34d407cdb0a03b4b914d148a41d36deb4b4632
0
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
package org.apache.lucene.benchmark.byTask.feeds; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.Closeable; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Calendar; import java.util.Map; import java.util.Properties; import java.util.Locale; import java.util.Random; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; import java.text.SimpleDateFormat; import java.text.ParsePosition; import org.apache.lucene.benchmark.byTask.utils.Config; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.NumericField; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; /** * Creates {@link Document} objects. Uses a {@link ContentSource} to generate * {@link DocData} objects. Supports the following parameters: * <ul> * <li><b>content.source</b> - specifies the {@link ContentSource} class to use * (default <b>SingleDocSource</b>). * <li><b>doc.stored</b> - specifies whether fields should be stored (default * <b>false</b>). * <li><b>doc.body.stored</b> - specifies whether the body field should be stored (default * = <b>doc.stored</b>). * <li><b>doc.tokenized</b> - specifies whether fields should be tokenized * (default <b>true</b>). * <li><b>doc.body.tokenized</b> - specifies whether the * body field should be tokenized (default = <b>doc.tokenized</b>). * <li><b>doc.tokenized.norms</b> - specifies whether norms should be stored in * the index or not. (default <b>false</b>). * <li><b>doc.body.tokenized.norms</b> - specifies whether norms should be * stored in the index for the body field. This can be set to true, while * <code>doc.tokenized.norms</code> is set to false, to allow norms storing just * for the body field. (default <b>true</b>). * <li><b>doc.term.vector</b> - specifies whether term vectors should be stored * for fields (default <b>false</b>). * <li><b>doc.term.vector.positions</b> - specifies whether term vectors should * be stored with positions (default <b>false</b>). * <li><b>doc.term.vector.offsets</b> - specifies whether term vectors should be * stored with offsets (default <b>false</b>). * <li><b>doc.store.body.bytes</b> - specifies whether to store the raw bytes of * the document's content in the document (default <b>false</b>). * <li><b>doc.reuse.fields</b> - specifies whether Field and Document objects * should be reused (default <b>true</b>). * <li><b>doc.index.props</b> - specifies whether the properties returned by * <li><b>doc.random.id.limit</b> - if specified, docs will be assigned random * IDs from 0 to this limit. This is useful with UpdateDoc * for testing performance of IndexWriter.updateDocument. * {@link DocData#getProps()} will be indexed. (default <b>false</b>). * </ul> */ public class DocMaker implements Closeable { private static class LeftOver { private DocData docdata; private int cnt; } private Random r; private int updateDocIDLimit; static class DocState { private final Map<String,Field> fields; private final Map<String,NumericField> numericFields; private final boolean reuseFields; final Document doc; DocData docData = new DocData(); public DocState(boolean reuseFields, FieldType ft, FieldType bodyFt) { this.reuseFields = reuseFields; if (reuseFields) { fields = new HashMap<String,Field>(); numericFields = new HashMap<String,NumericField>(); // Initialize the map with the default fields. fields.put(BODY_FIELD, new Field(BODY_FIELD, "", bodyFt)); fields.put(TITLE_FIELD, new Field(TITLE_FIELD, "", ft)); fields.put(DATE_FIELD, new Field(DATE_FIELD, "", ft)); fields.put(ID_FIELD, new Field(ID_FIELD, "", StringField.TYPE_STORED)); fields.put(NAME_FIELD, new Field(NAME_FIELD, "", ft)); numericFields.put(DATE_MSEC_FIELD, new NumericField(DATE_MSEC_FIELD, 0L)); numericFields.put(TIME_SEC_FIELD, new NumericField(TIME_SEC_FIELD, 0)); doc = new Document(); } else { numericFields = null; fields = null; doc = null; } } /** * Returns a field corresponding to the field name. If * <code>reuseFields</code> was set to true, then it attempts to reuse a * Field instance. If such a field does not exist, it creates a new one. */ Field getField(String name, FieldType ft) { if (!reuseFields) { return new Field(name, "", ft); } Field f = fields.get(name); if (f == null) { f = new Field(name, "", ft); fields.put(name, f); } return f; } NumericField getNumericField(String name, NumericField.DataType type) { NumericField f; if (reuseFields) { f = numericFields.get(name); } else { f = null; } if (f == null) { switch(type) { case INT: f = new NumericField(name, 0); break; case LONG: f = new NumericField(name, 0L); break; case FLOAT: f = new NumericField(name, 0.0f); break; case DOUBLE: f = new NumericField(name, 0.0); break; default: assert false; } if (reuseFields) { numericFields.put(name, f); } } return f; } } private boolean storeBytes = false; private static class DateUtil { public SimpleDateFormat parser = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss", Locale.US); public Calendar cal = Calendar.getInstance(); public ParsePosition pos = new ParsePosition(0); public DateUtil() { parser.setLenient(true); } } // leftovers are thread local, because it is unsafe to share residues between threads private ThreadLocal<LeftOver> leftovr = new ThreadLocal<LeftOver>(); private ThreadLocal<DocState> docState = new ThreadLocal<DocState>(); private ThreadLocal<DateUtil> dateParsers = new ThreadLocal<DateUtil>(); public static final String BODY_FIELD = "body"; public static final String TITLE_FIELD = "doctitle"; public static final String DATE_FIELD = "docdate"; public static final String DATE_MSEC_FIELD = "docdatenum"; public static final String TIME_SEC_FIELD = "doctimesecnum"; public static final String ID_FIELD = "docid"; public static final String BYTES_FIELD = "bytes"; public static final String NAME_FIELD = "docname"; protected Config config; protected FieldType valType; protected FieldType bodyValType; protected ContentSource source; protected boolean reuseFields; protected boolean indexProperties; private final AtomicInteger numDocsCreated = new AtomicInteger(); public DocMaker() { } // create a doc // use only part of the body, modify it to keep the rest (or use all if size==0). // reset the docdata properties so they are not added more than once. private Document createDocument(DocData docData, int size, int cnt) throws UnsupportedEncodingException { final DocState ds = getDocState(); final Document doc = reuseFields ? ds.doc : new Document(); doc.getFields().clear(); // Set ID_FIELD FieldType ft = new FieldType(valType); ft.setIndexed(true); Field idField = ds.getField(ID_FIELD, ft); int id; if (r != null) { id = r.nextInt(updateDocIDLimit); } else { id = docData.getID(); if (id == -1) { id = numDocsCreated.getAndIncrement(); } } idField.setValue(Integer.toString(id)); doc.add(idField); // Set NAME_FIELD String name = docData.getName(); if (name == null) name = ""; name = cnt < 0 ? name : name + "_" + cnt; Field nameField = ds.getField(NAME_FIELD, valType); nameField.setValue(name); doc.add(nameField); // Set DATE_FIELD DateUtil util = dateParsers.get(); if (util == null) { util = new DateUtil(); dateParsers.set(util); } Date date = null; String dateString = docData.getDate(); if (dateString != null) { util.pos.setIndex(0); date = util.parser.parse(dateString, util.pos); //System.out.println(dateString + " parsed to " + date); } else { dateString = ""; } Field dateStringField = ds.getField(DATE_FIELD, valType); dateStringField.setValue(dateString); doc.add(dateStringField); if (date == null) { // just set to right now date = new Date(); } NumericField dateField = ds.getNumericField(DATE_MSEC_FIELD, NumericField.DataType.LONG); dateField.setValue(date.getTime()); doc.add(dateField); util.cal.setTime(date); final int sec = util.cal.get(Calendar.HOUR_OF_DAY)*3600 + util.cal.get(Calendar.MINUTE)*60 + util.cal.get(Calendar.SECOND); NumericField timeSecField = ds.getNumericField(TIME_SEC_FIELD, NumericField.DataType.INT); timeSecField.setValue(sec); doc.add(timeSecField); // Set TITLE_FIELD String title = docData.getTitle(); Field titleField = ds.getField(TITLE_FIELD, valType); titleField.setValue(title == null ? "" : title); doc.add(titleField); String body = docData.getBody(); if (body != null && body.length() > 0) { String bdy; if (size <= 0 || size >= body.length()) { bdy = body; // use all docData.setBody(""); // nothing left } else { // attempt not to break words - if whitespace found within next 20 chars... for (int n = size - 1; n < size + 20 && n < body.length(); n++) { if (Character.isWhitespace(body.charAt(n))) { size = n; break; } } bdy = body.substring(0, size); // use part docData.setBody(body.substring(size)); // some left } Field bodyField = ds.getField(BODY_FIELD, bodyValType); bodyField.setValue(bdy); doc.add(bodyField); if (storeBytes) { Field bytesField = ds.getField(BYTES_FIELD, StringField.TYPE_STORED); bytesField.setValue(bdy.getBytes("UTF-8")); doc.add(bytesField); } } if (indexProperties) { Properties props = docData.getProps(); if (props != null) { for (final Map.Entry<Object,Object> entry : props.entrySet()) { Field f = ds.getField((String) entry.getKey(), valType); f.setValue((String) entry.getValue()); doc.add(f); } docData.setProps(null); } } //System.out.println("============== Created doc "+numDocsCreated+" :\n"+doc+"\n=========="); return doc; } private void resetLeftovers() { leftovr.set(null); } protected DocState getDocState() { DocState ds = docState.get(); if (ds == null) { ds = new DocState(reuseFields, valType, bodyValType); docState.set(ds); } return ds; } /** * Closes the {@link DocMaker}. The base implementation closes the * {@link ContentSource}, and it can be overridden to do more work (but make * sure to call super.close()). */ public void close() throws IOException { source.close(); } /** * Returns the number of bytes generated by the content source since last * reset. */ public synchronized long getBytesCount() { return source.getBytesCount(); } /** * Returns the total number of bytes that were generated by the content source * defined to that doc maker. */ public long getTotalBytesCount() { return source.getTotalBytesCount(); } /** * Creates a {@link Document} object ready for indexing. This method uses the * {@link ContentSource} to get the next document from the source, and creates * a {@link Document} object from the returned fields. If * <code>reuseFields</code> was set to true, it will reuse {@link Document} * and {@link Field} instances. */ public Document makeDocument() throws Exception { resetLeftovers(); DocData docData = source.getNextDocData(getDocState().docData); Document doc = createDocument(docData, 0, -1); return doc; } /** * Same as {@link #makeDocument()}, only this method creates a document of the * given size input by <code>size</code>. */ public Document makeDocument(int size) throws Exception { LeftOver lvr = leftovr.get(); if (lvr == null || lvr.docdata == null || lvr.docdata.getBody() == null || lvr.docdata.getBody().length() == 0) { resetLeftovers(); } DocData docData = getDocState().docData; DocData dd = (lvr == null ? source.getNextDocData(docData) : lvr.docdata); int cnt = (lvr == null ? 0 : lvr.cnt); while (dd.getBody() == null || dd.getBody().length() < size) { DocData dd2 = dd; dd = source.getNextDocData(new DocData()); cnt = 0; dd.setBody(dd2.getBody() + dd.getBody()); } Document doc = createDocument(dd, size, cnt); if (dd.getBody() == null || dd.getBody().length() == 0) { resetLeftovers(); } else { if (lvr == null) { lvr = new LeftOver(); leftovr.set(lvr); } lvr.docdata = dd; lvr.cnt = ++cnt; } return doc; } /** Reset inputs so that the test run would behave, input wise, as if it just started. */ public synchronized void resetInputs() throws IOException { source.printStatistics("docs"); // re-initiate since properties by round may have changed. setConfig(config); source.resetInputs(); numDocsCreated.set(0); resetLeftovers(); } /** Set the configuration parameters of this doc maker. */ public void setConfig(Config config) { this.config = config; try { if (source != null) { source.close(); } String sourceClass = config.get("content.source", "org.apache.lucene.benchmark.byTask.feeds.SingleDocSource"); source = Class.forName(sourceClass).asSubclass(ContentSource.class).newInstance(); source.setConfig(config); } catch (Exception e) { // Should not get here. Throw runtime exception. throw new RuntimeException(e); } boolean stored = config.get("doc.stored", false); boolean bodyStored = config.get("doc.body.stored", stored); boolean tokenized = config.get("doc.tokenized", true); boolean bodyTokenized = config.get("doc.body.tokenized", tokenized); boolean norms = config.get("doc.tokenized.norms", false); boolean bodyNorms = config.get("doc.body.tokenized.norms", true); boolean termVec = config.get("doc.term.vector", false); boolean termVecPositions = config.get("doc.term.vector.positions", false); boolean termVecOffsets = config.get("doc.term.vector.offsets", false); valType = new FieldType(TextField.TYPE_UNSTORED); valType.setStored(stored); valType.setTokenized(tokenized); valType.setOmitNorms(!norms); valType.setStoreTermVectors(termVec); valType.setStoreTermVectorPositions(termVecPositions); valType.setStoreTermVectorOffsets(termVecOffsets); valType.freeze(); bodyValType = new FieldType(TextField.TYPE_UNSTORED); bodyValType.setStored(bodyStored); bodyValType.setTokenized(bodyTokenized); bodyValType.setOmitNorms(!bodyNorms); bodyValType.setStoreTermVectors(termVec); bodyValType.setStoreTermVectorPositions(termVecPositions); bodyValType.setStoreTermVectorOffsets(termVecOffsets); bodyValType.freeze(); storeBytes = config.get("doc.store.body.bytes", false); reuseFields = config.get("doc.reuse.fields", true); // In a multi-rounds run, it is important to reset DocState since settings // of fields may change between rounds, and this is the only way to reset // the cache of all threads. docState = new ThreadLocal<DocState>(); indexProperties = config.get("doc.index.props", false); updateDocIDLimit = config.get("doc.random.id.limit", -1); if (updateDocIDLimit != -1) { r = new Random(179); } } }
modules/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/DocMaker.java
package org.apache.lucene.benchmark.byTask.feeds; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.Closeable; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Calendar; import java.util.Map; import java.util.Properties; import java.util.Locale; import java.util.Random; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; import java.text.SimpleDateFormat; import java.text.ParsePosition; import org.apache.lucene.benchmark.byTask.utils.Config; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.NumericField; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; /** * Creates {@link Document} objects. Uses a {@link ContentSource} to generate * {@link DocData} objects. Supports the following parameters: * <ul> * <li><b>content.source</b> - specifies the {@link ContentSource} class to use * (default <b>SingleDocSource</b>). * <li><b>doc.stored</b> - specifies whether fields should be stored (default * <b>false</b>). * <li><b>doc.body.stored</b> - specifies whether the body field should be stored (default * = <b>doc.stored</b>). * <li><b>doc.tokenized</b> - specifies whether fields should be tokenized * (default <b>true</b>). * <li><b>doc.body.tokenized</b> - specifies whether the * body field should be tokenized (default = <b>doc.tokenized</b>). * <li><b>doc.tokenized.norms</b> - specifies whether norms should be stored in * the index or not. (default <b>false</b>). * <li><b>doc.body.tokenized.norms</b> - specifies whether norms should be * stored in the index for the body field. This can be set to true, while * <code>doc.tokenized.norms</code> is set to false, to allow norms storing just * for the body field. (default <b>true</b>). * <li><b>doc.term.vector</b> - specifies whether term vectors should be stored * for fields (default <b>false</b>). * <li><b>doc.term.vector.positions</b> - specifies whether term vectors should * be stored with positions (default <b>false</b>). * <li><b>doc.term.vector.offsets</b> - specifies whether term vectors should be * stored with offsets (default <b>false</b>). * <li><b>doc.store.body.bytes</b> - specifies whether to store the raw bytes of * the document's content in the document (default <b>false</b>). * <li><b>doc.reuse.fields</b> - specifies whether Field and Document objects * should be reused (default <b>true</b>). * <li><b>doc.index.props</b> - specifies whether the properties returned by * <li><b>doc.random.id.limit</b> - if specified, docs will be assigned random * IDs from 0 to this limit. This is useful with UpdateDoc * for testing performance of IndexWriter.updateDocument. * {@link DocData#getProps()} will be indexed. (default <b>false</b>). * </ul> */ public class DocMaker implements Closeable { private static class LeftOver { private DocData docdata; private int cnt; } private Random r; private int updateDocIDLimit; static class DocState { private final Map<String,Field> fields; private final Map<String,NumericField> numericFields; private final boolean reuseFields; final Document doc; DocData docData = new DocData(); public DocState(boolean reuseFields, FieldType ft, FieldType bodyFt) { this.reuseFields = reuseFields; if (reuseFields) { fields = new HashMap<String,Field>(); numericFields = new HashMap<String,NumericField>(); // Initialize the map with the default fields. fields.put(BODY_FIELD, new Field(BODY_FIELD, "", bodyFt)); fields.put(TITLE_FIELD, new Field(TITLE_FIELD, "", ft)); fields.put(DATE_FIELD, new Field(DATE_FIELD, "", ft)); fields.put(ID_FIELD, new Field(ID_FIELD, "", StringField.TYPE_STORED)); fields.put(NAME_FIELD, new Field(NAME_FIELD, "", ft)); numericFields.put(DATE_MSEC_FIELD, new NumericField(DATE_MSEC_FIELD, 0L)); numericFields.put(TIME_SEC_FIELD, new NumericField(TIME_SEC_FIELD, 0)); doc = new Document(); } else { numericFields = null; fields = null; doc = null; } } /** * Returns a field corresponding to the field name. If * <code>reuseFields</code> was set to true, then it attempts to reuse a * Field instance. If such a field does not exist, it creates a new one. */ Field getField(String name, FieldType ft) { if (!reuseFields) { return new Field(name, "", ft); } Field f = fields.get(name); if (f == null) { f = new Field(name, "", ft); fields.put(name, f); } return f; } NumericField getNumericField(String name, NumericField.DataType type) { NumericField f; if (reuseFields) { f = numericFields.get(name); } else { f = null; } if (f == null) { switch(type) { case INT: f = new NumericField(name, 0); break; case LONG: f = new NumericField(name, 0L); break; case FLOAT: f = new NumericField(name, 0.0f); break; case DOUBLE: f = new NumericField(name, 0.0); break; default: assert false; } if (reuseFields) { numericFields.put(name, f); } } return f; } } private boolean storeBytes = false; private static class DateUtil { public SimpleDateFormat parser = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss", Locale.US); public Calendar cal = Calendar.getInstance(); public ParsePosition pos = new ParsePosition(0); public DateUtil() { parser.setLenient(true); } } // leftovers are thread local, because it is unsafe to share residues between threads private ThreadLocal<LeftOver> leftovr = new ThreadLocal<LeftOver>(); private ThreadLocal<DocState> docState = new ThreadLocal<DocState>(); private ThreadLocal<DateUtil> dateParsers = new ThreadLocal<DateUtil>(); public static final String BODY_FIELD = "body"; public static final String TITLE_FIELD = "doctitle"; public static final String DATE_FIELD = "docdate"; public static final String DATE_MSEC_FIELD = "docdatenum"; public static final String TIME_SEC_FIELD = "doctimesecnum"; public static final String ID_FIELD = "docid"; public static final String BYTES_FIELD = "bytes"; public static final String NAME_FIELD = "docname"; protected Config config; protected FieldType valType; protected FieldType bodyValType; protected ContentSource source; protected boolean reuseFields; protected boolean indexProperties; private final AtomicInteger numDocsCreated = new AtomicInteger(); public DocMaker() { } // create a doc // use only part of the body, modify it to keep the rest (or use all if size==0). // reset the docdata properties so they are not added more than once. private Document createDocument(DocData docData, int size, int cnt) throws UnsupportedEncodingException { final DocState ds = getDocState(); final Document doc = reuseFields ? ds.doc : new Document(); doc.getFields().clear(); // Set ID_FIELD FieldType ft = new FieldType(valType); ft.setIndexed(true); Field idField = ds.getField(ID_FIELD, ft); int id; if (r != null) { id = r.nextInt(updateDocIDLimit); } else { id = docData.getID(); if (id == -1) { id = numDocsCreated.getAndIncrement(); } } idField.setValue(Integer.toString(id)); doc.add(idField); // Set NAME_FIELD String name = docData.getName(); if (name == null) name = ""; name = cnt < 0 ? name : name + "_" + cnt; Field nameField = ds.getField(NAME_FIELD, valType); nameField.setValue(name); doc.add(nameField); // Set DATE_FIELD DateUtil util = dateParsers.get(); if (util == null) { util = new DateUtil(); dateParsers.set(util); } Date date = null; String dateString = docData.getDate(); if (dateString != null) { util.pos.setIndex(0); date = util.parser.parse(dateString, util.pos); //System.out.println(dateString + " parsed to " + date); } else { dateString = ""; } Field dateStringField = ds.getField(DATE_FIELD, valType); dateStringField.setValue(dateString); doc.add(dateStringField); if (date == null) { // just set to right now date = new Date(); } NumericField dateField = ds.getNumericField(DATE_MSEC_FIELD, NumericField.DataType.LONG); dateField.setValue(date.getTime()); doc.add(dateField); util.cal.setTime(date); final int sec = util.cal.get(Calendar.HOUR_OF_DAY)*3600 + util.cal.get(Calendar.MINUTE)*60 + util.cal.get(Calendar.SECOND); NumericField timeSecField = ds.getNumericField(TIME_SEC_FIELD, NumericField.DataType.INT); timeSecField.setValue(sec); doc.add(timeSecField); // Set TITLE_FIELD String title = docData.getTitle(); Field titleField = ds.getField(TITLE_FIELD, valType); titleField.setValue(title == null ? "" : title); doc.add(titleField); String body = docData.getBody(); if (body != null && body.length() > 0) { String bdy; if (size <= 0 || size >= body.length()) { bdy = body; // use all docData.setBody(""); // nothing left } else { // attempt not to break words - if whitespace found within next 20 chars... for (int n = size - 1; n < size + 20 && n < body.length(); n++) { if (Character.isWhitespace(body.charAt(n))) { size = n; break; } } bdy = body.substring(0, size); // use part docData.setBody(body.substring(size)); // some left } Field bodyField = ds.getField(BODY_FIELD, bodyValType); bodyField.setValue(bdy); doc.add(bodyField); if (storeBytes) { Field bytesField = ds.getField(BYTES_FIELD, StringField.TYPE_STORED); bytesField.setValue(bdy.getBytes("UTF-8")); doc.add(bytesField); } } if (indexProperties) { Properties props = docData.getProps(); if (props != null) { for (final Map.Entry<Object,Object> entry : props.entrySet()) { Field f = ds.getField((String) entry.getKey(), valType); f.setValue((String) entry.getValue()); doc.add(f); } docData.setProps(null); } } //System.out.println("============== Created doc "+numDocsCreated+" :\n"+doc+"\n=========="); return doc; } private void resetLeftovers() { leftovr.set(null); } protected DocState getDocState() { DocState ds = docState.get(); if (ds == null) { ds = new DocState(reuseFields, valType, bodyValType); docState.set(ds); } return ds; } /** * Closes the {@link DocMaker}. The base implementation closes the * {@link ContentSource}, and it can be overridden to do more work (but make * sure to call super.close()). */ public void close() throws IOException { source.close(); } /** * Returns the number of bytes generated by the content source since last * reset. */ public synchronized long getBytesCount() { return source.getBytesCount(); } /** * Returns the total number of bytes that were generated by the content source * defined to that doc maker. */ public long getTotalBytesCount() { return source.getTotalBytesCount(); } /** * Creates a {@link Document} object ready for indexing. This method uses the * {@link ContentSource} to get the next document from the source, and creates * a {@link Document} object from the returned fields. If * <code>reuseFields</code> was set to true, it will reuse {@link Document} * and {@link Field} instances. */ public Document makeDocument() throws Exception { resetLeftovers(); DocData docData = source.getNextDocData(getDocState().docData); Document doc = createDocument(docData, 0, -1); return doc; } /** * Same as {@link #makeDocument()}, only this method creates a document of the * given size input by <code>size</code>. */ public Document makeDocument(int size) throws Exception { LeftOver lvr = leftovr.get(); if (lvr == null || lvr.docdata == null || lvr.docdata.getBody() == null || lvr.docdata.getBody().length() == 0) { resetLeftovers(); } DocData docData = getDocState().docData; DocData dd = (lvr == null ? source.getNextDocData(docData) : lvr.docdata); int cnt = (lvr == null ? 0 : lvr.cnt); while (dd.getBody() == null || dd.getBody().length() < size) { DocData dd2 = dd; dd = source.getNextDocData(new DocData()); cnt = 0; dd.setBody(dd2.getBody() + dd.getBody()); } Document doc = createDocument(dd, size, cnt); if (dd.getBody() == null || dd.getBody().length() == 0) { resetLeftovers(); } else { if (lvr == null) { lvr = new LeftOver(); leftovr.set(lvr); } lvr.docdata = dd; lvr.cnt = ++cnt; } return doc; } /** Reset inputs so that the test run would behave, input wise, as if it just started. */ public synchronized void resetInputs() throws IOException { source.printStatistics("docs"); // re-initiate since properties by round may have changed. setConfig(config); source.resetInputs(); numDocsCreated.set(0); resetLeftovers(); } /** Set the configuration parameters of this doc maker. */ public void setConfig(Config config) { this.config = config; try { if (source != null) { source.close(); } String sourceClass = config.get("content.source", "org.apache.lucene.benchmark.byTask.feeds.SingleDocSource"); source = Class.forName(sourceClass).asSubclass(ContentSource.class).newInstance(); source.setConfig(config); } catch (Exception e) { // Should not get here. Throw runtime exception. throw new RuntimeException(e); } boolean stored = config.get("doc.stored", false); boolean bodyStored = config.get("doc.body.stored", stored); boolean tokenized = config.get("doc.tokenized", true); boolean bodyTokenized = config.get("doc.body.tokenized", tokenized); boolean norms = config.get("doc.tokenized.norms", false); boolean bodyNorms = config.get("doc.body.tokenized.norms", true); boolean termVec = config.get("doc.term.vector", false); boolean termVecPositions = config.get("doc.term.vector.positions", false); boolean termVecOffsets = config.get("doc.term.vector.offsets", false); valType = new FieldType(TextField.TYPE_UNSTORED); valType.setStored(stored); valType.setTokenized(tokenized); valType.setOmitNorms(!norms); valType.setStoreTermVectors(termVec); valType.setStoreTermVectorPositions(termVecPositions); valType.setStoreTermVectorOffsets(termVecOffsets); valType.freeze(); bodyValType = new FieldType(TextField.TYPE_UNSTORED); bodyValType.setStored(bodyStored); bodyValType.setTokenized(bodyTokenized); bodyValType.setOmitNorms(!bodyNorms); bodyValType.setStoreTermVectors(termVec); bodyValType.setStoreTermVectorPositions(termVecPositions); bodyValType.setStoreTermVectorOffsets(termVecOffsets); bodyValType.freeze(); storeBytes = config.get("doc.store.body.bytes", false); reuseFields = config.get("doc.reuse.fields", true); // In a multi-rounds run, it is important to reset DocState since settings // of fields may change between rounds, and this is the only way to reset // the cache of all threads. docState = new ThreadLocal<DocState>(); indexProperties = config.get("doc.index.props", false); updateDocIDLimit = config.get("doc.random.id.limit", -1); if (updateDocIDLimit != -1) { r = new Random(179); } } }
fix DocMaker file handle leak: now with the actual fix :) git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1244380 13f79535-47bb-0310-9956-ffa450edef68
modules/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/DocMaker.java
fix DocMaker file handle leak: now with the actual fix :)
<ide><path>odules/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/DocMaker.java <ide> public void setConfig(Config config) { <ide> this.config = config; <ide> try { <del> if (source != null) { <del> source.close(); <del> } <add> if (source != null) { <add> source.close(); <add> } <ide> String sourceClass = config.get("content.source", "org.apache.lucene.benchmark.byTask.feeds.SingleDocSource"); <ide> source = Class.forName(sourceClass).asSubclass(ContentSource.class).newInstance(); <ide> source.setConfig(config);
JavaScript
mit
05f9c0383e0738359c14d26e40a43a8cc92fbe6a
0
Hidden-Mia/Roleplay-PS,Hidden-Mia/Roleplay-PS
/** * * Slots.js Made By Dragotic. * Slots is a casino game. * **/ 'use strict'; // To get hash colors of the names const color = require('../config/color'); // Available slots for the game const slots = { 'bulbasaur': 3, 'squirtle': 6, 'charmander': 9, 'pikachu': 12, 'eevee': 15, 'snorlax': 18, 'dragonite': 21, 'mew': 24, 'mewtwo': 27, }; function currencyName (amount) { let name = " buck"; return name; } // Trozei sprites for each pokemon const slotsTrozei = { 'bulbasaur': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/bulbasaur.gif', 'squirtle': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/squirtle.gif', 'charmander': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/charmander.gif', 'pikachu': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/pikachu.gif', 'eevee': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/eevee.gif', 'snorlax': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/snorlax.gif', 'dragonite': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/dragonite.gif', 'mew': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/mew.gif', 'mewtwo': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/mewtwo.gif', }; const availableSlots = Object.keys(slots); function spin() { return availableSlots[Math.floor(Math.random() * availableSlots.length)]; }; function rng() { return Math.floor(Math.random() * 100); }; function display(result, user, slotOne, slotTwo, slotThree) { let display = '<div style="padding: 3px; background: #000000; padding: 5px; border-radius: 5px; text-align: center;">' + '<center><img src="http://i.imgur.com/p2nObtE.gif" width="300" height="70"></center><br />' + '<center><img style="padding: 3px; border: 1px inset gold; border-radius: 5px; box-shadow: inset 1px 1px 5px white;" src="' + slotsTrozei[slotOne] + '">&nbsp;&nbsp;&nbsp;' + '<img style="padding: 3px; border: 1px inset gold; border-radius: 5px; box-shadow: inset 1px 1px 5px white;" src="' + slotsTrozei[slotTwo] + '">&nbsp;&nbsp;&nbsp;' + '<img style="padding: 3px; border: 1px inset gold; border-radius: 5px; box-shadow: inset 1px 1px 5px white;" src="' + slotsTrozei[slotThree] + '"></center>' + '<font style="color: white;"><br />'; if (!result) { display += 'Aww... bad luck, <b><font color="' + color(user) + '">' + user + '</font></b>. Better luck next time!</font>'; } if (result) { display += 'Congratulations, <b><font color="' + color(user) + '">' + user + '</font></b>. You have won ' + slots[slotOne] + ' bucks!!</font>'; } return display + '</div>'; }; exports.commands = { slots: { start: 'spin', spin: function(target, room ,user) { if (room.id !== 'casino') return this.errorReply('Casino games can only be played in the "Casino".'); if (!this.canBroadcast()) return false; if (!this.canTalk()) return this.errorReply('/slots spin - Access Denied.'); const amount = Db('money').get(user.userid, 0); if (amount < 3) return this.errorReply('You don\'t have enough bucks to play this game. You need ' + (3 - amount) + currencyName(amount) + ' more.'); const result = spin(); const chancePercentage = rng(); const chancesGenerated = 70 + availableSlots.indexOf(result) * 3; if (chancePercentage >= chancesGenerated) { Db('money').set(user.userid, (amount + slots[result])); return this.sendReplyBox(display(true, user.name, result, result, result)); } // Incase all outcomes are same, it'll resort to changing the first one. let outcomeOne = spin(); let outcomeTwo = spin(); let outcomeThree = spin(); while (outcomeOne === outcomeTwo && outcomeTwo === outcomeThree) { outcomeOne = spin(); } Db('money').set(user.userid, (amount - 3)); return this.sendReplyBox(display(false, user.name, outcomeOne, outcomeTwo, outcomeThree)); }, '': function(target, room, user) { return this.parse('/help slots'); }, }, slotshelp: ['Slots is a casino game. ' + 'It awards the user with varying amount of bucks depending on the streak of pokemon they user gets.' + '\n' + 'Following Are Slots Winnings: \n' + 'Bulbasaur : 3 bucks' + '\n' + 'Squirtle : 6 bucks' + '\n' + 'Charmander: 9 bucks' + '\n' + 'Pikachu : 12 bucks' + '\n' + 'Eevee : 15 bucks' + '\n' + 'Snorlax : 17 bucks' + '\n' + 'Dragonite : 21 bucks' + '\n' + 'Mew : 24 bucks' + '\n' + 'Mewtwo : 27 bucks' + '\n' + 'Use "/slots spin" to play the game.'], };
chat-plugins/slots.js
/** * * Slots.js Made By Dragotic. * Slots is a casino game. * **/ 'use strict'; // To get hash colors of the names const color = require('../config/color'); // Available slots for the game const slots = { 'bulbasaur': 3, 'squirtle': 6, 'charmander': 9, 'pikachu': 12, 'eevee': 15, 'snorlax': 18, 'dragonite': 21, 'mew': 24, 'mewtwo': 27, }; function currencyName (amount) { let name = " buck"; return name; } // Trozei sprites for each pokemon const slotsTrozei = { 'bulbasaur': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/bulbasaur.gif', 'squirtle': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/squirtle.gif', 'charmander': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/charmander.gif', 'pikachu': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/pikachu.gif', 'eevee': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/eevee.gif', 'snorlax': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/snorlax.gif', 'dragonite': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/dragonite.gif', 'mew': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/mew.gif', 'mewtwo': 'http://www.pokestadium.com/assets/img/sprites/misc/trozei/mewtwo.gif', }; const availableSlots = Object.keys(slots); function spin() { return availableSlots[Math.floor(Math.random() * availableSlots.length)]; }; function rng() { return Math.floor(Math.random() * 100); }; function display(result, user, slotOne, slotTwo, slotThree) { let display = '<div style="padding: 3px; background: #000000; padding: 5px; border-radius: 5px; text-align: center;">' + '<center><img src="http://i.imgur.com/p2nObtE.gif" width="300" height="70"></center><br />' + '<center><img style="padding: 3px; border: 1px inset gold; border-radius: 5px; box-shadow: inset 1px 1px 5px white;" src="' + slotsTrozei[slotOne] + '">&nbsp;&nbsp;&nbsp;' + '<img style="padding: 3px; border: 1px inset gold; border-radius: 5px; box-shadow: inset 1px 1px 5px white;" src="' + slotsTrozei[slotTwo] + '">&nbsp;&nbsp;&nbsp;' + '<img style="padding: 3px; border: 1px inset gold; border-radius: 5px; box-shadow: inset 1px 1px 5px white;" src="' + slotsTrozei[slotThree] + '"></center>' + '<font style="color: white;"><br />'; if (!result) { display += 'Aww... bad luck, <b><font color="' + color(user) + '">' + user + '</font></b>. Better luck next time!</font>'; } if (result) { display += 'Congratulations, <b><font color="' + color(user) + '">' + user + '</font></b>. You have won ' + slots[slotOne] + ' bucks!!</font>'; } return display + '</div>'; }; exports.commands = { slots: { start: 'spin', spin: function(target, room ,user) { if (room.id !== 'casino') return this.errorReply('Casino games can only be played in the "Casino".'); if (!this.canTalk()) return this.errorReply('/slots spin - Access Denied.'); const amount = Db('money').get(user.userid, 0); if (amount < 3) return this.errorReply('You don\'t have enough bucks to play this game. You need ' + (3 - amount) + currencyName(amount) + ' more.'); const result = spin(); const chancePercentage = rng(); const chancesGenerated = 70 + availableSlots.indexOf(result) * 3; if (chancePercentage >= chancesGenerated) { Db('money').set(user.userid, (amount + slots[result])); return this.sendReplyBox(display(true, user.name, result, result, result)); } // Incase all outcomes are same, it'll resort to changing the first one. let outcomeOne = spin(); let outcomeTwo = spin(); let outcomeThree = spin(); while (outcomeOne === outcomeTwo && outcomeTwo === outcomeThree) { outcomeOne = spin(); } Db('money').set(user.userid, (amount - 3)); return this.sendReplyBox(display(false, user.name, outcomeOne, outcomeTwo, outcomeThree)); }, '': function(target, room, user) { return this.parse('/help slots'); }, }, slotshelp: ['Slots is a casino game. ' + 'It awards the user with varying amount of bucks depending on the streak of pokemon they user gets.' + '\n' + 'Following Are Slots Winnings: \n' + 'Bulbasaur : 3 bucks' + '\n' + 'Squirtle : 6 bucks' + '\n' + 'Charmander: 9 bucks' + '\n' + 'Pikachu : 12 bucks' + '\n' + 'Eevee : 15 bucks' + '\n' + 'Snorlax : 17 bucks' + '\n' + 'Dragonite : 21 bucks' + '\n' + 'Mew : 24 bucks' + '\n' + 'Mewtwo : 27 bucks' + '\n' + 'Use "/slots spin" to play the game.'], };
Update slots.js
chat-plugins/slots.js
Update slots.js
<ide><path>hat-plugins/slots.js <ide> start: 'spin', <ide> spin: function(target, room ,user) { <ide> if (room.id !== 'casino') return this.errorReply('Casino games can only be played in the "Casino".'); <add> if (!this.canBroadcast()) return false; <ide> if (!this.canTalk()) return this.errorReply('/slots spin - Access Denied.'); <ide> <ide> const amount = Db('money').get(user.userid, 0);
Java
apache-2.0
7655dfd559ca8093433130b741e043b30c932efb
0
zawn/cas,PetrGasparik/cas,yisiqi/cas,yisiqi/cas,yisiqi/cas,PetrGasparik/cas,zawn/cas,PetrGasparik/cas,zawn/cas,zhoffice/cas,zawn/cas,PetrGasparik/cas,zhoffice/cas,yisiqi/cas,zhoffice/cas,zhoffice/cas
package org.jasig.cas.web.flow; import org.jasig.cas.authentication.AccountDisabledException; import org.jasig.cas.authentication.AccountPasswordMustChangeException; import org.jasig.cas.authentication.AuthenticationException; import org.jasig.cas.authentication.InvalidLoginLocationException; import org.jasig.cas.authentication.InvalidLoginTimeException; import org.jasig.cas.services.UnauthorizedServiceForPrincipalException; import org.jasig.cas.ticket.AbstractTicketException; import org.jasig.cas.ticket.UnsatisfiedAuthenticationPolicyException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.binding.message.MessageBuilder; import org.springframework.binding.message.MessageContext; import org.springframework.stereotype.Component; import javax.security.auth.login.AccountLockedException; import javax.security.auth.login.AccountNotFoundException; import javax.security.auth.login.CredentialExpiredException; import javax.security.auth.login.FailedLoginException; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; /** * Performs two important error handling functions on an {@link AuthenticationException} raised from the authentication * layer: * * <ol> * <li>Maps handler errors onto message bundle strings for display to user.</li> * <li>Determines the next webflow state by comparing handler errors against {@link #errors} * in list order. The first entry that matches determines the outcome state, which * is the simple class name of the exception.</li> * </ol> * * @author Marvin S. Addison * @since 4.0.0 */ @Component("authenticationExceptionHandler") public class AuthenticationExceptionHandler { /** State name when no matching exception is found. */ private static final String UNKNOWN = "UNKNOWN"; /** Default message bundle prefix. */ private static final String DEFAULT_MESSAGE_BUNDLE_PREFIX = "authenticationFailure."; /** Default list of errors this class knows how to handle. */ private static final List<Class<? extends Exception>> DEFAULT_ERROR_LIST = new ArrayList<>(); private final Logger logger = LoggerFactory.getLogger(this.getClass()); static { DEFAULT_ERROR_LIST.add(AccountLockedException.class); DEFAULT_ERROR_LIST.add(FailedLoginException.class); DEFAULT_ERROR_LIST.add(CredentialExpiredException.class); DEFAULT_ERROR_LIST.add(AccountNotFoundException.class); DEFAULT_ERROR_LIST.add(AccountDisabledException.class); DEFAULT_ERROR_LIST.add(InvalidLoginLocationException.class); DEFAULT_ERROR_LIST.add(AccountPasswordMustChangeException.class); DEFAULT_ERROR_LIST.add(InvalidLoginTimeException.class); DEFAULT_ERROR_LIST.add(UnauthorizedServiceForPrincipalException.class); DEFAULT_ERROR_LIST.add(UnsatisfiedAuthenticationPolicyException.class); } /** Ordered list of error classes that this class knows how to handle. */ @NotNull private List<Class<? extends Exception>> errors = DEFAULT_ERROR_LIST; /** String appended to exception class name to create a message bundle key for that particular error. */ private String messageBundlePrefix = DEFAULT_MESSAGE_BUNDLE_PREFIX; /** * Sets the list of errors that this class knows how to handle. * * @param errors List of errors in order of descending precedence. */ public void setErrors(final List<Class<? extends Exception>> errors) { this.errors = errors; } public final List<Class<? extends Exception>> getErrors() { return Collections.unmodifiableList(this.errors); } /** * Sets the message bundle prefix appended to exception class names to create a message bundle key for that * particular error. * * @param prefix Prefix appended to exception names. */ public void setMessageBundlePrefix(final String prefix) { this.messageBundlePrefix = prefix; } /** * Maps an authentication exception onto a state name. Also sets an ERROR severity message in the message context. * * @param e Authentication error to handle. * @param messageContext the spring message context * @return Name of next flow state to transition to or {@value #UNKNOWN} */ public String handle(final Exception e, final MessageContext messageContext) { // handle AuthenticationExceptions if (e instanceof AuthenticationException) { return handleAuthenticationException((AuthenticationException) e, messageContext); } // handle AbstractTicketExceptions exceptions else if (e instanceof AbstractTicketException) { return handleAbstractTicketException((AbstractTicketException) e, messageContext); } else { // we don't recognize this exception logger.trace("Unable to translate handler errors of the authentication exception {}. " + "Returning {} by default...", e, UNKNOWN); final String messageCode = this.messageBundlePrefix + UNKNOWN; messageContext.addMessage(new MessageBuilder().error().code(messageCode).build()); return UNKNOWN; } } /** * Maps an authentication exception onto a state name equal to the simple class name of the {@link * AuthenticationException#getHandlerErrors()} with highest precedence. Also sets an ERROR severity message in the * message context of the form {@code [messageBundlePrefix][exceptionClassSimpleName]} for for the first handler * error that is configured. If no match is found, {@value #UNKNOWN} is returned. * * @param e Authentication error to handle. * @param messageContext the spring message context * @return Name of next flow state to transition to or {@value #UNKNOWN} */ private String handleAuthenticationException(final AuthenticationException e, final MessageContext messageContext) { // find the first error in the error list that matches the handlerErrors final String handlerErrorName = this.errors.stream().filter(e.getHandlerErrors().values()::contains) .map(Class::getSimpleName).findFirst().orElseGet(() -> { logger.error("Unable to translate handler errors of the authentication exception {}. " + "Returning {} by default...", e, UNKNOWN); return UNKNOWN; }); // output message and return handlerErrorName final String messageCode = this.messageBundlePrefix + handlerErrorName; messageContext.addMessage(new MessageBuilder().error().code(messageCode).build()); return handlerErrorName; } /** * Maps an {@link AbstractTicketException} onto a state name equal to the simple class name of the exception with * highest precedence. Also sets an ERROR severity message in the message context with the error code found in * {@link AbstractTicketException#getCode()}. If no match is found, {@value #UNKNOWN} is returned. * * @param e Ticket exception to handle. * @param messageContext the spring message context * @return Name of next flow state to transition to or {@value #UNKNOWN} */ private String handleAbstractTicketException(final AbstractTicketException e, final MessageContext messageContext) { // find the first error in the error list that matches the AbstractTicketException final Optional<String> match = this.errors.stream().filter((c) -> c.isInstance(e)).map(Class::getSimpleName) .findFirst(); // for AbstractTicketExceptions we only output messages for errors in the errors list if (match.isPresent()) { // use the RootCasException.getCode() for the message code messageContext.addMessage(new MessageBuilder().error().code(((AbstractTicketException) e).getCode()) .build()); } // return the matched simple class name return match.orElse(UNKNOWN); } }
cas-server-core-authentication/src/main/java/org/jasig/cas/web/flow/AuthenticationExceptionHandler.java
package org.jasig.cas.web.flow; import org.jasig.cas.authentication.AccountDisabledException; import org.jasig.cas.authentication.AccountPasswordMustChangeException; import org.jasig.cas.authentication.AuthenticationException; import org.jasig.cas.authentication.InvalidLoginLocationException; import org.jasig.cas.authentication.InvalidLoginTimeException; import org.jasig.cas.services.UnauthorizedServiceForPrincipalException; import org.jasig.cas.ticket.AbstractTicketException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.binding.message.MessageBuilder; import org.springframework.binding.message.MessageContext; import org.springframework.stereotype.Component; import javax.security.auth.login.AccountLockedException; import javax.security.auth.login.AccountNotFoundException; import javax.security.auth.login.CredentialExpiredException; import javax.security.auth.login.FailedLoginException; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; /** * Performs two important error handling functions on an {@link AuthenticationException} raised from the authentication * layer: * * <ol> * <li>Maps handler errors onto message bundle strings for display to user.</li> * <li>Determines the next webflow state by comparing handler errors against {@link #errors} * in list order. The first entry that matches determines the outcome state, which * is the simple class name of the exception.</li> * </ol> * * @author Marvin S. Addison * @since 4.0.0 */ @Component("authenticationExceptionHandler") public class AuthenticationExceptionHandler { /** State name when no matching exception is found. */ private static final String UNKNOWN = "UNKNOWN"; /** Default message bundle prefix. */ private static final String DEFAULT_MESSAGE_BUNDLE_PREFIX = "authenticationFailure."; /** Default list of errors this class knows how to handle. */ private static final List<Class<? extends Exception>> DEFAULT_ERROR_LIST = new ArrayList<>(); private final Logger logger = LoggerFactory.getLogger(this.getClass()); static { DEFAULT_ERROR_LIST.add(AccountLockedException.class); DEFAULT_ERROR_LIST.add(FailedLoginException.class); DEFAULT_ERROR_LIST.add(CredentialExpiredException.class); DEFAULT_ERROR_LIST.add(AccountNotFoundException.class); DEFAULT_ERROR_LIST.add(AccountDisabledException.class); DEFAULT_ERROR_LIST.add(InvalidLoginLocationException.class); DEFAULT_ERROR_LIST.add(AccountPasswordMustChangeException.class); DEFAULT_ERROR_LIST.add(InvalidLoginTimeException.class); DEFAULT_ERROR_LIST.add(UnauthorizedServiceForPrincipalException.class); } /** Ordered list of error classes that this class knows how to handle. */ @NotNull private List<Class<? extends Exception>> errors = DEFAULT_ERROR_LIST; /** String appended to exception class name to create a message bundle key for that particular error. */ private String messageBundlePrefix = DEFAULT_MESSAGE_BUNDLE_PREFIX; /** * Sets the list of errors that this class knows how to handle. * * @param errors List of errors in order of descending precedence. */ public void setErrors(final List<Class<? extends Exception>> errors) { this.errors = errors; } public final List<Class<? extends Exception>> getErrors() { return Collections.unmodifiableList(this.errors); } /** * Sets the message bundle prefix appended to exception class names to create a message bundle key for that * particular error. * * @param prefix Prefix appended to exception names. */ public void setMessageBundlePrefix(final String prefix) { this.messageBundlePrefix = prefix; } /** * Maps an authentication exception onto a state name. Also sets an ERROR severity message in the message context. * * @param e Authentication error to handle. * @param messageContext the spring message context * @return Name of next flow state to transition to or {@value #UNKNOWN} */ public String handle(final Exception e, final MessageContext messageContext) { // handle AuthenticationExceptions if (e instanceof AuthenticationException) { return handleAuthenticationException((AuthenticationException) e, messageContext); } // handle AbstractTicketExceptions exceptions else if (e instanceof AbstractTicketException) { return handleAbstractTicketException((AbstractTicketException) e, messageContext); } else { // we don't recognize this exception logger.trace("Unable to translate handler errors of the authentication exception {}. " + "Returning {} by default...", e, UNKNOWN); final String messageCode = this.messageBundlePrefix + UNKNOWN; messageContext.addMessage(new MessageBuilder().error().code(messageCode).build()); return UNKNOWN; } } /** * Maps an authentication exception onto a state name equal to the simple class name of the {@link * AuthenticationException#getHandlerErrors()} with highest precedence. Also sets an ERROR severity message in the * message context of the form {@code [messageBundlePrefix][exceptionClassSimpleName]} for for the first handler * error that is configured. If no match is found, {@value #UNKNOWN} is returned. * * @param e Authentication error to handle. * @param messageContext the spring message context * @return Name of next flow state to transition to or {@value #UNKNOWN} */ private String handleAuthenticationException(final AuthenticationException e, final MessageContext messageContext) { // find the first error in the error list that matches the handlerErrors final String handlerErrorName = this.errors.stream().filter(e.getHandlerErrors().values()::contains) .map(Class::getSimpleName).findFirst().orElseGet(() -> { logger.error("Unable to translate handler errors of the authentication exception {}. " + "Returning {} by default...", e, UNKNOWN); return UNKNOWN; }); // output message and return handlerErrorName final String messageCode = this.messageBundlePrefix + handlerErrorName; messageContext.addMessage(new MessageBuilder().error().code(messageCode).build()); return handlerErrorName; } /** * Maps an {@link AbstractTicketException} onto a state name equal to the simple class name of the exception with * highest precedence. Also sets an ERROR severity message in the message context with the error code found in * {@link AbstractTicketException#getCode()}. If no match is found, {@value #UNKNOWN} is returned. * * @param e Ticket exception to handle. * @param messageContext the spring message context * @return Name of next flow state to transition to or {@value #UNKNOWN} */ private String handleAbstractTicketException(final AbstractTicketException e, final MessageContext messageContext) { // find the first error in the error list that matches the AbstractTicketException final Optional<String> match = this.errors.stream().filter((c) -> c.isInstance(e)).map(Class::getSimpleName) .findFirst(); // for AbstractTicketExceptions we only output messages for errors in the errors list if (match.isPresent()) { // use the RootCasException.getCode() for the message code messageContext.addMessage(new MessageBuilder().error().code(((AbstractTicketException) e).getCode()) .build()); } // return the matched simple class name return match.orElse(UNKNOWN); } }
add UnsatisfiedAuthenticationPolicyException to default list of error codes
cas-server-core-authentication/src/main/java/org/jasig/cas/web/flow/AuthenticationExceptionHandler.java
add UnsatisfiedAuthenticationPolicyException to default list of error codes
<ide><path>as-server-core-authentication/src/main/java/org/jasig/cas/web/flow/AuthenticationExceptionHandler.java <ide> import org.jasig.cas.authentication.InvalidLoginTimeException; <ide> import org.jasig.cas.services.UnauthorizedServiceForPrincipalException; <ide> import org.jasig.cas.ticket.AbstractTicketException; <add>import org.jasig.cas.ticket.UnsatisfiedAuthenticationPolicyException; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> import org.springframework.binding.message.MessageBuilder; <ide> DEFAULT_ERROR_LIST.add(AccountPasswordMustChangeException.class); <ide> DEFAULT_ERROR_LIST.add(InvalidLoginTimeException.class); <ide> DEFAULT_ERROR_LIST.add(UnauthorizedServiceForPrincipalException.class); <add> DEFAULT_ERROR_LIST.add(UnsatisfiedAuthenticationPolicyException.class); <ide> } <ide> <ide> /** Ordered list of error classes that this class knows how to handle. */
Java
mit
452b48faf96f187e6b9d5a40e4cc0a35292d78eb
0
Adyen/adyen-java-api-library,Adyen/adyen-java-api-library,Adyen/adyen-java-api-library
/* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Java API Library * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.model; import java.util.List; import java.util.Objects; import com.adyen.Util.Util; import com.adyen.constants.ApiConstants; import com.adyen.model.additionalData.InvoiceLine; import com.adyen.model.additionalData.SplitPayment; import com.adyen.model.additionalData.SplitPaymentItem; import com.google.gson.annotations.SerializedName; /** * PaymentRequest */ public class PaymentRequest extends AbstractPaymentRequest<PaymentRequest> { private static final String ADDITIONAL_DATA = "/authorise-3d-adyen-response"; @SerializedName("card") private Card card = null; @SerializedName("mpiData") private ThreeDSecureData mpiData = null; @SerializedName("bankAccount") private BankAccount bankAccount = null; @SerializedName("store") private Long store = null; /** * how the shopper interacts with the system */ public enum RecurringProcessingModelEnum { @SerializedName("Subscription") SUBSCRIPTION("Subscription"), @SerializedName("CardOnFile") CARD_ON_FILE("CardOnFile"); private String value; RecurringProcessingModelEnum(String value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } } @SerializedName("recurringProcessingModel") private RecurringProcessingModelEnum recurringProcessingModel = null; public PaymentRequest setAmountData(String amount, String currency) { Amount amountData = Util.createAmount(amount, currency); this.setAmount(amountData); return this; } public PaymentRequest setCSEToken(String cseToken) { getOrCreateAdditionalData().put(ApiConstants.AdditionalData.Card.Encrypted.JSON, cseToken); return this; } public PaymentRequest setCardData(String cardNumber, String cardHolder, String expiryMonth, String expiryYear, String cvc) { Card card = new Card(); card.setExpiryMonth(expiryMonth); card.setExpiryYear(expiryYear); card.setHolderName(cardHolder); card.setNumber(cardNumber); card.setCvc(cvc); this.setCard(card); return this; } /** * Set Data needed for payment request using secured fields */ public PaymentRequest setSecuredFieldsData(String encryptedCardNumber, String cardHolder, String encryptedExpiryMonth, String encryptedExpiryYear, String encryptedSecurityCode) { this.setCardHolder(cardHolder) .setEncryptedCardNumber(encryptedCardNumber) .setEncryptedExpiryMonth(encryptedExpiryMonth) .setEncryptedExpiryYear(encryptedExpiryYear) .setEncryptedSecurityCode(encryptedSecurityCode); return this; } public PaymentRequest setCardHolder(String cardHolder) { if (card == null) { card = new Card(); } card.setHolderName(cardHolder); return this; } public PaymentRequest setEncryptedCardNumber(String encryptedCardNumber) { getOrCreateAdditionalData().put(ApiConstants.AdditionalData.ENCRYPTED_CARD_NUMBER, encryptedCardNumber); return this; } public PaymentRequest setEncryptedExpiryMonth(String encryptedExpiryMonth) { getOrCreateAdditionalData().put(ApiConstants.AdditionalData.ENCRYPTED_EXPIRY_MONTH, encryptedExpiryMonth); return this; } public PaymentRequest setEncryptedExpiryYear(String encryptedExpiryYear) { getOrCreateAdditionalData().put(ApiConstants.AdditionalData.ENCRYPTED_EXPIRY_YEAR, encryptedExpiryYear); return this; } public PaymentRequest setEncryptedSecurityCode(String encryptedSecurityCode) { getOrCreateAdditionalData().put(ApiConstants.AdditionalData.ENCRYPTED_SECURITY_CODE, encryptedSecurityCode); return this; } public PaymentRequest setPaymentToken(String paymentToken) { getOrCreateAdditionalData().put(ApiConstants.AdditionalData.PAYMENT_TOKEN, paymentToken); return this; } public RecurringProcessingModelEnum getRecurringProcessingModel() { return recurringProcessingModel; } public PaymentRequest setRecurringProcessingModel(RecurringProcessingModelEnum recurringProcessingModel) { this.recurringProcessingModel = recurringProcessingModel; return this; } /** * Set invoiceLines in addtionalData */ public PaymentRequest setInvoiceLines(List<InvoiceLine> invoiceLines) { Integer count = 1; for (InvoiceLine invoiceLine : invoiceLines) { StringBuilder sb = new StringBuilder(); sb.append("openinvoicedata.line"); sb.append(Integer.toString(count)); String lineNumber = sb.toString(); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".currencyCode").toString(), invoiceLine.getCurrencyCode()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".description").toString(), invoiceLine.getDescription()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".itemAmount").toString(), invoiceLine.getItemAmount().toString()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".itemVatAmount").toString(), invoiceLine.getItemVATAmount().toString()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".itemVatPercentage").toString(), invoiceLine.getItemVatPercentage().toString()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".numberOfItems").toString(), Integer.toString(invoiceLine.getNumberOfItems())); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".vatCategory").toString(), invoiceLine.getVatCategory().toString()); // Addional field only for RatePay if (invoiceLine.getItemId() != null && ! invoiceLine.getItemId().isEmpty()) { this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".itemId").toString(), invoiceLine.getItemId()); } count++; } this.getOrCreateAdditionalData().put("openinvoicedata.numberOfLines", Integer.toString(invoiceLines.size())); return this; } public PaymentRequest setSplitPayment(SplitPayment splitPayment) { this.getOrCreateAdditionalData().put("split.api", splitPayment.getApi().toString()); this.getOrCreateAdditionalData().put("split.totalAmount", splitPayment.getTotalAmount().toString()); this.getOrCreateAdditionalData().put("split.currencyCode", splitPayment.getCurrencyCode()); Integer count = 1; for (SplitPaymentItem splitPaymentItem : splitPayment.getSplitPaymentItems()) { StringBuilder sb = new StringBuilder(); sb.append("split.item"); sb.append(Integer.toString(count)); String lineNumber = sb.toString(); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".amount").toString(), splitPaymentItem.getAmount().toString()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".type").toString(), splitPaymentItem.getType()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".account").toString(), splitPaymentItem.getAccount()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".reference").toString(), splitPaymentItem.getReference()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".description").toString(), splitPaymentItem.getDescription()); count++; } this.getOrCreateAdditionalData().put("split.nrOfItems", Integer.toString(splitPayment.getSplitPaymentItems().size())); return this; } public PaymentRequest card(Card card) { this.card = card; return this; } /** * a representation of a (credit or debit) card * * @return card **/ public Card getCard() { return card; } public void setCard(Card card) { this.card = card; } public PaymentRequest mpiData(ThreeDSecureData mpiData) { this.mpiData = mpiData; return this; } /** * authentication data produced by an MPI (MasterCard SecureCode or Verified By Visa) * * @return mpiData **/ public ThreeDSecureData getMpiData() { return mpiData; } public void setMpiData(ThreeDSecureData mpiData) { this.mpiData = mpiData; } public PaymentRequest bankAccount(BankAccount bankAccount) { this.bankAccount = bankAccount; return this; } /** * a representation of a bank account * * @return bankAccount **/ public BankAccount getBankAccount() { return bankAccount; } public void setBankAccount(BankAccount bankAccount) { this.bankAccount = bankAccount; } public PaymentRequest store(Long store) { this.store = store; return this; } /** * store id from which the payment request is made from * * @return store **/ public Long getStore() { return store; } public void setStore(Long store) { this.store = store; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PaymentRequest paymentRequest = (PaymentRequest) o; return super.equals(paymentRequest) && Objects.equals(this.card, paymentRequest.card) && Objects.equals(this.mpiData, paymentRequest.mpiData) && Objects.equals(this.bankAccount, paymentRequest.bankAccount) && Objects.equals(this.store, paymentRequest.store); } @Override public int hashCode() { return Objects.hash(card, mpiData, bankAccount, super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PaymentRequest {\n"); sb.append(super.toString()); sb.append(" mpiData: ").append(toIndentedString(mpiData)).append("\n"); sb.append(" bankAccount: ").append(toIndentedString(bankAccount)).append("\n"); sb.append(" recurringProcessingModel: ").append(toIndentedString(recurringProcessingModel)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
src/main/java/com/adyen/model/PaymentRequest.java
/* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Java API Library * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.model; import java.util.List; import java.util.Objects; import com.adyen.Util.Util; import com.adyen.constants.ApiConstants; import com.adyen.model.additionalData.InvoiceLine; import com.adyen.model.additionalData.SplitPayment; import com.adyen.model.additionalData.SplitPaymentItem; import com.google.gson.annotations.SerializedName; /** * PaymentRequest */ public class PaymentRequest extends AbstractPaymentRequest<PaymentRequest> { private static final String ADDITIONAL_DATA = "/authorise-3d-adyen-response"; @SerializedName("card") private Card card = null; @SerializedName("mpiData") private ThreeDSecureData mpiData = null; @SerializedName("bankAccount") private BankAccount bankAccount = null; /** * how the shopper interacts with the system */ public enum RecurringProcessingModelEnum { @SerializedName("Subscription") SUBSCRIPTION("Subscription"), @SerializedName("CardOnFile") CARD_ON_FILE("CardOnFile"); private String value; RecurringProcessingModelEnum(String value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } } @SerializedName("recurringProcessingModel") private RecurringProcessingModelEnum recurringProcessingModel = null; public PaymentRequest setAmountData(String amount, String currency) { Amount amountData = Util.createAmount(amount, currency); this.setAmount(amountData); return this; } public PaymentRequest setCSEToken(String cseToken) { getOrCreateAdditionalData().put(ApiConstants.AdditionalData.Card.Encrypted.JSON, cseToken); return this; } public PaymentRequest setCardData(String cardNumber, String cardHolder, String expiryMonth, String expiryYear, String cvc) { Card card = new Card(); card.setExpiryMonth(expiryMonth); card.setExpiryYear(expiryYear); card.setHolderName(cardHolder); card.setNumber(cardNumber); card.setCvc(cvc); this.setCard(card); return this; } /** * Set Data needed for payment request using secured fields */ public PaymentRequest setSecuredFieldsData(String encryptedCardNumber, String cardHolder, String encryptedExpiryMonth, String encryptedExpiryYear, String encryptedSecurityCode) { this.setCardHolder(cardHolder) .setEncryptedCardNumber(encryptedCardNumber) .setEncryptedExpiryMonth(encryptedExpiryMonth) .setEncryptedExpiryYear(encryptedExpiryYear) .setEncryptedSecurityCode(encryptedSecurityCode); return this; } public PaymentRequest setCardHolder(String cardHolder) { if (card == null) { card = new Card(); } card.setHolderName(cardHolder); return this; } public PaymentRequest setEncryptedCardNumber(String encryptedCardNumber) { getOrCreateAdditionalData().put(ApiConstants.AdditionalData.ENCRYPTED_CARD_NUMBER, encryptedCardNumber); return this; } public PaymentRequest setEncryptedExpiryMonth(String encryptedExpiryMonth) { getOrCreateAdditionalData().put(ApiConstants.AdditionalData.ENCRYPTED_EXPIRY_MONTH, encryptedExpiryMonth); return this; } public PaymentRequest setEncryptedExpiryYear(String encryptedExpiryYear) { getOrCreateAdditionalData().put(ApiConstants.AdditionalData.ENCRYPTED_EXPIRY_YEAR, encryptedExpiryYear); return this; } public PaymentRequest setEncryptedSecurityCode(String encryptedSecurityCode) { getOrCreateAdditionalData().put(ApiConstants.AdditionalData.ENCRYPTED_SECURITY_CODE, encryptedSecurityCode); return this; } public PaymentRequest setPaymentToken(String paymentToken) { getOrCreateAdditionalData().put(ApiConstants.AdditionalData.PAYMENT_TOKEN, paymentToken); return this; } public RecurringProcessingModelEnum getRecurringProcessingModel() { return recurringProcessingModel; } public PaymentRequest setRecurringProcessingModel(RecurringProcessingModelEnum recurringProcessingModel) { this.recurringProcessingModel = recurringProcessingModel; return this; } /** * Set invoiceLines in addtionalData */ public PaymentRequest setInvoiceLines(List<InvoiceLine> invoiceLines) { Integer count = 1; for (InvoiceLine invoiceLine : invoiceLines) { StringBuilder sb = new StringBuilder(); sb.append("openinvoicedata.line"); sb.append(Integer.toString(count)); String lineNumber = sb.toString(); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".currencyCode").toString(), invoiceLine.getCurrencyCode()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".description").toString(), invoiceLine.getDescription()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".itemAmount").toString(), invoiceLine.getItemAmount().toString()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".itemVatAmount").toString(), invoiceLine.getItemVATAmount().toString()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".itemVatPercentage").toString(), invoiceLine.getItemVatPercentage().toString()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".numberOfItems").toString(), Integer.toString(invoiceLine.getNumberOfItems())); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".vatCategory").toString(), invoiceLine.getVatCategory().toString()); // Addional field only for RatePay if (invoiceLine.getItemId() != null && ! invoiceLine.getItemId().isEmpty()) { this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".itemId").toString(), invoiceLine.getItemId()); } count++; } this.getOrCreateAdditionalData().put("openinvoicedata.numberOfLines", Integer.toString(invoiceLines.size())); return this; } public PaymentRequest setSplitPayment(SplitPayment splitPayment) { this.getOrCreateAdditionalData().put("split.api", splitPayment.getApi().toString()); this.getOrCreateAdditionalData().put("split.totalAmount", splitPayment.getTotalAmount().toString()); this.getOrCreateAdditionalData().put("split.currencyCode", splitPayment.getCurrencyCode()); Integer count = 1; for (SplitPaymentItem splitPaymentItem : splitPayment.getSplitPaymentItems()) { StringBuilder sb = new StringBuilder(); sb.append("split.item"); sb.append(Integer.toString(count)); String lineNumber = sb.toString(); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".amount").toString(), splitPaymentItem.getAmount().toString()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".type").toString(), splitPaymentItem.getType()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".account").toString(), splitPaymentItem.getAccount()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".reference").toString(), splitPaymentItem.getReference()); this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".description").toString(), splitPaymentItem.getDescription()); count++; } this.getOrCreateAdditionalData().put("split.nrOfItems", Integer.toString(splitPayment.getSplitPaymentItems().size())); return this; } public PaymentRequest card(Card card) { this.card = card; return this; } /** * a representation of a (credit or debit) card * * @return card **/ public Card getCard() { return card; } public void setCard(Card card) { this.card = card; } public PaymentRequest mpiData(ThreeDSecureData mpiData) { this.mpiData = mpiData; return this; } /** * authentication data produced by an MPI (MasterCard SecureCode or Verified By Visa) * * @return mpiData **/ public ThreeDSecureData getMpiData() { return mpiData; } public void setMpiData(ThreeDSecureData mpiData) { this.mpiData = mpiData; } public PaymentRequest bankAccount(BankAccount bankAccount) { this.bankAccount = bankAccount; return this; } /** * a representation of a bank account * * @return bankAccount **/ public BankAccount getBankAccount() { return bankAccount; } public void setBankAccount(BankAccount bankAccount) { this.bankAccount = bankAccount; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PaymentRequest paymentRequest = (PaymentRequest) o; return super.equals(paymentRequest) && Objects.equals(this.card, paymentRequest.card) && Objects.equals(this.mpiData, paymentRequest.mpiData) && Objects.equals(this.bankAccount, paymentRequest.bankAccount); } @Override public int hashCode() { return Objects.hash(card, mpiData, bankAccount, super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PaymentRequest {\n"); sb.append(super.toString()); sb.append(" mpiData: ").append(toIndentedString(mpiData)).append("\n"); sb.append(" bankAccount: ").append(toIndentedString(bankAccount)).append("\n"); sb.append(" recurringProcessingModel: ").append(toIndentedString(recurringProcessingModel)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
Add store to payment request
src/main/java/com/adyen/model/PaymentRequest.java
Add store to payment request
<ide><path>rc/main/java/com/adyen/model/PaymentRequest.java <ide> @SerializedName("bankAccount") <ide> private BankAccount bankAccount = null; <ide> <add> @SerializedName("store") <add> private Long store = null; <add> <ide> /** <ide> * how the shopper interacts with the system <ide> */ <ide> this.bankAccount = bankAccount; <ide> } <ide> <add> public PaymentRequest store(Long store) { <add> this.store = store; <add> return this; <add> } <add> <add> /** <add> * store id from which the payment request is made from <add> * <add> * @return store <add> **/ <add> public Long getStore() { <add> return store; <add> } <add> <add> public void setStore(Long store) { <add> this.store = store; <add> } <add> <ide> @Override <ide> public boolean equals(Object o) { <ide> if (this == o) { <ide> return false; <ide> } <ide> PaymentRequest paymentRequest = (PaymentRequest) o; <del> return super.equals(paymentRequest) && Objects.equals(this.card, paymentRequest.card) && Objects.equals(this.mpiData, paymentRequest.mpiData) && Objects.equals(this.bankAccount, <del> paymentRequest.bankAccount); <add> return super.equals(paymentRequest) <add> && Objects.equals(this.card, paymentRequest.card) <add> && Objects.equals(this.mpiData, paymentRequest.mpiData) <add> && Objects.equals(this.bankAccount, paymentRequest.bankAccount) <add> && Objects.equals(this.store, paymentRequest.store); <ide> } <ide> <ide> @Override <ide> } <ide> <ide> } <del>
Java
apache-2.0
043536a05ed80e7674babe2b06c3640880090217
0
JNOSQL/diana-driver,JNOSQL/diana-driver
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.jnosql.diana.redis.key; import org.jnosql.diana.api.key.BucketManagerFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.not; import static org.junit.jupiter.api.Assertions.*; public class RedisListStringTest { private static final String FRUITS = "fruits-string"; private BucketManagerFactory keyValueEntityManagerFactory; private List<String> fruits; @BeforeEach public void init() { keyValueEntityManagerFactory = RedisTestUtils.get(); fruits = keyValueEntityManagerFactory.getList(FRUITS, String.class); } @Test public void shouldReturnsList() { assertNotNull(fruits); } @Test public void shouldAddList() { assertTrue(fruits.isEmpty()); fruits.add("banana"); assertFalse(fruits.isEmpty()); String banana = fruits.get(0); assertNotNull(banana); assertEquals(banana, "banana"); } @Test public void shouldSetList() { fruits.add("banana"); fruits.add(0, "orange"); assertTrue(fruits.size() == 2); assertEquals(fruits.get(0), "orange"); assertEquals(fruits.get(1), "banana"); fruits.set(0, "waterMelon"); assertEquals(fruits.get(0), "waterMelon"); assertEquals(fruits.get(1), "banana"); } @Test public void shouldRemoveList() { fruits.add("banana"); fruits.add("orange"); fruits.add("watermellon"); fruits.remove("banana"); assertThat(fruits, not(contains("banana"))); } @Test public void shouldReturnIndexOf() { fruits.add("orange"); fruits.add("banana"); fruits.add("watermellon"); fruits.add("banana"); assertTrue(fruits.indexOf("banana") == 1); assertTrue(fruits.lastIndexOf("banana") == 3); assertTrue(fruits.contains("banana")); assertTrue(fruits.indexOf("melon") == -1); assertTrue(fruits.lastIndexOf("melon") == -1); } @Test public void shouldReturnContains() { fruits.add("orange"); fruits.add("banana"); fruits.add("watermellon"); assertTrue(fruits.contains("banana")); assertFalse(fruits.contains("melon")); assertTrue(fruits.containsAll(Arrays.asList("banana", "orange"))); assertFalse(fruits.containsAll(Arrays.asList("banana", "melon"))); } @SuppressWarnings("unused") @Test public void shouldIterate() { fruits.add("melon"); fruits.add("banana"); int count = 0; for (String fruiCart : fruits) { count++; } assertTrue(count == 2); fruits.remove(0); fruits.remove(0); count = 0; for (String fruiCart : fruits) { count++; } assertTrue(count == 0); } @Test public void shouldClear(){ fruits.add("orange"); fruits.add("banana"); fruits.add("watermellon"); fruits.clear(); assertTrue(fruits.isEmpty()); } @AfterEach public void end() { fruits.clear(); } }
redis-driver/src/test/java/org/jnosql/diana/redis/key/RedisListStringTest.java
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.jnosql.diana.redis.key; import org.jnosql.diana.api.key.BucketManagerFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.not; import static org.junit.jupiter.api.Assertions.*; public class RedisListStringTest { private static final String FRUITS = "fruits-string"; private BucketManagerFactory keyValueEntityManagerFactory; private List<String> fruits; @BeforeEach public void init() { keyValueEntityManagerFactory = RedisTestUtils.get(); fruits = keyValueEntityManagerFactory.getList(FRUITS, String.class); } @Test public void shouldReturnsList() { assertNotNull(fruits); } @Test public void shouldAddList() { assertTrue(fruits.isEmpty()); fruits.add("banana"); assertFalse(fruits.isEmpty()); String banana = fruits.get(0); assertNotNull(banana); assertEquals(banana, "banana"); } @Test public void shouldSetList() { fruits.add("banana"); fruits.add(0, "orange"); assertTrue(fruits.size() == 2); assertEquals(fruits.get(0), "orange"); assertEquals(fruits.get(1), "banana"); fruits.set(0, "waterMelon"); assertEquals(fruits.get(0), "waterMelon"); assertEquals(fruits.get(1), "banana"); } @Test public void shouldRemoveList() { fruits.add("banana"); fruits.add("orange"); fruits.add("watermellon"); fruits.remove("banana"); assertThat(fruits, not(contains("banana"))); } @Test public void shouldReturnIndexOf() { fruits.add("orange"); fruits.add("banana"); fruits.add("watermellon"); fruits.add("banana"); assertTrue(fruits.indexOf("banana") == 1); assertTrue(fruits.lastIndexOf("banana") == 3); assertTrue(fruits.contains("banana")); assertTrue(fruits.indexOf("melon") == -1); assertTrue(fruits.lastIndexOf("melon") == -1); } @Test public void shouldReturnContains() { fruits.add("orange"); fruits.add("banana"); fruits.add("watermellon"); assertTrue(fruits.contains("banana")); assertFalse(fruits.contains("melon")); assertTrue(fruits.containsAll(Arrays.asList("banana", "orange"))); assertFalse(fruits.containsAll(Arrays.asList("banana", "melon"))); } @SuppressWarnings("unused") @Test public void shouldIterate() { fruits.add("melon"); fruits.add("banana"); int count = 0; for (String fruiCart : fruits) { count++; } assertTrue(count == 2); fruits.remove(0); fruits.remove(0); count = 0; for (String fruiCart : fruits) { count++; } assertTrue(count == 0); } @AfterEach public void end() { fruits.clear(); } }
Add list clear() test method Signed-off-by: Lucas Furlaneto <[email protected]>
redis-driver/src/test/java/org/jnosql/diana/redis/key/RedisListStringTest.java
Add list clear() test method
<ide><path>edis-driver/src/test/java/org/jnosql/diana/redis/key/RedisListStringTest.java <ide> assertTrue(count == 0); <ide> } <ide> <add> @Test <add> public void shouldClear(){ <add> fruits.add("orange"); <add> fruits.add("banana"); <add> fruits.add("watermellon"); <add> <add> fruits.clear(); <add> assertTrue(fruits.isEmpty()); <add> } <add> <ide> @AfterEach <ide> public void end() { <ide> fruits.clear();
Java
mit
error: pathspec 'myTransport/src/tgc2010/ui/dialog/LocateDialog.java' did not match any file(s) known to git
f47edcd044163bc82a93998c0235d4372d1ed5dc
1
lvanni/synapse,lvanni/synapse,lvanni/synapse,lvanni/synapse,lvanni/synapse,lvanni/synapse
package tgc2010.ui.dialog; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class LocateDialog extends Dialog{ private Color red = new Color(null, 255, 0, 0); public LocateDialog(final Shell parent) { super(parent); Display display = getParent().getDisplay(); /* Init the shell */ final Shell shell = new Shell(getParent(), SWT.BORDER | SWT.CLOSE); shell.setText("Locate Dialog"); FormLayout layout = new FormLayout(); layout.marginHeight = 5; layout.marginWidth = 5; shell.setLayout(layout); Label addess = new Label(shell, SWT.NONE); addess.setText("Address:"); FormData addressData = new FormData(); addressData.top = new FormAttachment(0, 0); addressData.left = new FormAttachment(0, 2); addess.setLayoutData(addressData); final Text addressText = new Text(shell, SWT.BORDER); FormData addressTextFormData = new FormData(); addressTextFormData.width = 200; addressTextFormData.height = 15; addressTextFormData.top = new FormAttachment(0, 0); addressTextFormData.left = new FormAttachment(0, 100); addressText.setLayoutData(addressTextFormData); Label zip = new Label(shell, SWT.NONE); zip.setText("Zip code:"); FormData zipFormeData = new FormData(); zipFormeData.top = new FormAttachment(addess, 0); zipFormeData.left = new FormAttachment(0, 0); zip.setLayoutData(zipFormeData); final Text zipText = new Text(shell, SWT.BORDER); FormData zipTextFormData = new FormData(); zipTextFormData.width = 200; zipTextFormData.height = 15; zipTextFormData.top = new FormAttachment(addess, 0); zipTextFormData.left = new FormAttachment(0, 100); zipText.setLayoutData(zipTextFormData); Label city = new Label(shell, SWT.NONE); city.setText("City:"); FormData cityFormeData = new FormData(); cityFormeData.top = new FormAttachment(zip, 0); cityFormeData.left = new FormAttachment(0, 0); city.setLayoutData(cityFormeData); final Text cityText = new Text(shell, SWT.BORDER); FormData cityTextFormData = new FormData(); cityTextFormData.width = 200; cityTextFormData.height = 15; cityTextFormData.top = new FormAttachment(zip, 0); cityTextFormData.left = new FormAttachment(0, 100); cityText.setLayoutData(cityTextFormData); // button "SEND" final Button okButton = new Button(shell, SWT.PUSH); okButton.setText("Send"); okButton.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { search(addressText.getText(), zipText.getText(), cityText.getText()); shell.close(); } }); FormData okFormData = new FormData(); okFormData.width = 80; okFormData.top = new FormAttachment(city, 0); okFormData.left = new FormAttachment(0, 0); okButton.setLayoutData(okFormData); shell.setDefaultButton(okButton); // button "CANCEL" final Button cancelButton = new Button(shell, SWT.PUSH); cancelButton.setText("Cancel"); cancelButton.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { shell.close(); } }); FormData cancelFormData = new FormData(); cancelFormData.width = 80; cancelFormData.top = new FormAttachment(city, 0); cancelFormData.left = new FormAttachment(okButton, 0); cancelButton.setLayoutData(cancelFormData); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } public static void search(String address, String zipcode, String city) { String scheme = "http"; String authority = "maps.google.fr"; String path = "/maps"; String query = "f=q&hl=fr&q=" + address+ " , " + zipcode + " " + city ; if(Desktop.isDesktopSupported()) { if(Desktop.getDesktop().isSupported(java.awt.Desktop.Action.BROWSE)) { try { URI uri = new URI(scheme, authority, path, query, null); System.out.println(uri.toASCIIString()); java.awt.Desktop.getDesktop().browse(uri); } catch (URISyntaxException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } else { //La fonction n'est pas supportée par votre système d'exploitation } } else { //Desktop pas supportée par votre système d'exploitation } } }
myTransport/src/tgc2010/ui/dialog/LocateDialog.java
GUI updated, Locate menu added git-svn-id: a05fd1a06364aada1baadae1fdc7fa09ea39c500@33 700752c6-984c-461e-9c28-e1bb893e44aa
myTransport/src/tgc2010/ui/dialog/LocateDialog.java
GUI updated, Locate menu added
<ide><path>yTransport/src/tgc2010/ui/dialog/LocateDialog.java <add>package tgc2010.ui.dialog; <add> <add>import java.awt.Desktop; <add>import java.io.IOException; <add>import java.net.URI; <add>import java.net.URISyntaxException; <add> <add>import org.eclipse.swt.SWT; <add>import org.eclipse.swt.events.SelectionAdapter; <add>import org.eclipse.swt.events.SelectionEvent; <add>import org.eclipse.swt.graphics.Color; <add>import org.eclipse.swt.layout.FormAttachment; <add>import org.eclipse.swt.layout.FormData; <add>import org.eclipse.swt.layout.FormLayout; <add>import org.eclipse.swt.widgets.Button; <add>import org.eclipse.swt.widgets.Dialog; <add>import org.eclipse.swt.widgets.Display; <add>import org.eclipse.swt.widgets.Label; <add>import org.eclipse.swt.widgets.Shell; <add>import org.eclipse.swt.widgets.Text; <add> <add>public class LocateDialog extends Dialog{ <add> <add> private Color red = new Color(null, 255, 0, 0); <add> <add> public LocateDialog(final Shell parent) { <add> super(parent); <add> Display display = getParent().getDisplay(); <add> <add> /* Init the shell */ <add> final Shell shell = new Shell(getParent(), SWT.BORDER | SWT.CLOSE); <add> shell.setText("Locate Dialog"); <add> FormLayout layout = new FormLayout(); <add> layout.marginHeight = 5; <add> layout.marginWidth = 5; <add> shell.setLayout(layout); <add> <add> Label addess = new Label(shell, SWT.NONE); <add> addess.setText("Address:"); <add> FormData addressData = new FormData(); <add> addressData.top = new FormAttachment(0, 0); <add> addressData.left = new FormAttachment(0, 2); <add> addess.setLayoutData(addressData); <add> <add> final Text addressText = new Text(shell, SWT.BORDER); <add> FormData addressTextFormData = new FormData(); <add> addressTextFormData.width = 200; <add> addressTextFormData.height = 15; <add> addressTextFormData.top = new FormAttachment(0, 0); <add> addressTextFormData.left = new FormAttachment(0, 100); <add> addressText.setLayoutData(addressTextFormData); <add> <add> Label zip = new Label(shell, SWT.NONE); <add> zip.setText("Zip code:"); <add> FormData zipFormeData = new FormData(); <add> zipFormeData.top = new FormAttachment(addess, 0); <add> zipFormeData.left = new FormAttachment(0, 0); <add> zip.setLayoutData(zipFormeData); <add> <add> final Text zipText = new Text(shell, SWT.BORDER); <add> FormData zipTextFormData = new FormData(); <add> zipTextFormData.width = 200; <add> zipTextFormData.height = 15; <add> zipTextFormData.top = new FormAttachment(addess, 0); <add> zipTextFormData.left = new FormAttachment(0, 100); <add> zipText.setLayoutData(zipTextFormData); <add> <add> Label city = new Label(shell, SWT.NONE); <add> city.setText("City:"); <add> FormData cityFormeData = new FormData(); <add> cityFormeData.top = new FormAttachment(zip, 0); <add> cityFormeData.left = new FormAttachment(0, 0); <add> city.setLayoutData(cityFormeData); <add> <add> final Text cityText = new Text(shell, SWT.BORDER); <add> FormData cityTextFormData = new FormData(); <add> cityTextFormData.width = 200; <add> cityTextFormData.height = 15; <add> cityTextFormData.top = new FormAttachment(zip, 0); <add> cityTextFormData.left = new FormAttachment(0, 100); <add> cityText.setLayoutData(cityTextFormData); <add> <add> // button "SEND" <add> final Button okButton = new Button(shell, SWT.PUSH); <add> okButton.setText("Send"); <add> okButton.addSelectionListener(new SelectionAdapter(){ <add> public void widgetSelected(SelectionEvent e) { <add> search(addressText.getText(), zipText.getText(), cityText.getText()); <add> shell.close(); <add> } <add> }); <add> FormData okFormData = new FormData(); <add> okFormData.width = 80; <add> okFormData.top = new FormAttachment(city, 0); <add> okFormData.left = new FormAttachment(0, 0); <add> okButton.setLayoutData(okFormData); <add> shell.setDefaultButton(okButton); <add> <add> // button "CANCEL" <add> final Button cancelButton = new Button(shell, SWT.PUSH); <add> cancelButton.setText("Cancel"); <add> cancelButton.addSelectionListener(new SelectionAdapter(){ <add> public void widgetSelected(SelectionEvent e) { <add> shell.close(); <add> } <add> }); <add> FormData cancelFormData = new FormData(); <add> cancelFormData.width = 80; <add> cancelFormData.top = new FormAttachment(city, 0); <add> cancelFormData.left = new FormAttachment(okButton, 0); <add> cancelButton.setLayoutData(cancelFormData); <add> <add> shell.pack(); <add> shell.open(); <add> <add> while (!shell.isDisposed()) { <add> if (!display.readAndDispatch()) { <add> display.sleep(); <add> } <add> } <add> } <add> <add> public static void search(String address, String zipcode, String city) { <add> String scheme = "http"; <add> String authority = "maps.google.fr"; <add> String path = "/maps"; <add> String query = "f=q&hl=fr&q=" + address+ " , " + zipcode + " " + city ; <add> if(Desktop.isDesktopSupported()) { <add> if(Desktop.getDesktop().isSupported(java.awt.Desktop.Action.BROWSE)) { <add> try { <add> URI uri = new URI(scheme, authority, path, query, null); <add> System.out.println(uri.toASCIIString()); <add> java.awt.Desktop.getDesktop().browse(uri); <add> } catch (URISyntaxException ex) { <add> ex.printStackTrace(); <add> } catch (IOException ex) { <add> ex.printStackTrace(); <add> } <add> } else { <add> //La fonction n'est pas supportée par votre système d'exploitation <add> } <add> } else { <add> //Desktop pas supportée par votre système d'exploitation <add> } <add> } <add>}
Java
apache-2.0
2515d2e8495c8b4e6aa2e4f3dafa199442183967
0
xfournet/intellij-community,apixandru/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,allotria/intellij-community,xfournet/intellij-community,asedunov/intellij-community,da1z/intellij-community,apixandru/intellij-community,da1z/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ibinti/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,signed/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,signed/intellij-community,da1z/intellij-community,signed/intellij-community,FHannes/intellij-community,ibinti/intellij-community,xfournet/intellij-community,allotria/intellij-community,FHannes/intellij-community,ibinti/intellij-community,semonte/intellij-community,signed/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ibinti/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,asedunov/intellij-community,semonte/intellij-community,asedunov/intellij-community,ibinti/intellij-community,asedunov/intellij-community,semonte/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,signed/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,signed/intellij-community,semonte/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,signed/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,signed/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,da1z/intellij-community,allotria/intellij-community,asedunov/intellij-community,allotria/intellij-community,FHannes/intellij-community,xfournet/intellij-community,xfournet/intellij-community,apixandru/intellij-community,semonte/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,apixandru/intellij-community,apixandru/intellij-community,xfournet/intellij-community,xfournet/intellij-community,FHannes/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,asedunov/intellij-community,allotria/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,signed/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,semonte/intellij-community,vvv1559/intellij-community,semonte/intellij-community,signed/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,xfournet/intellij-community,signed/intellij-community,asedunov/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ibinti/intellij-community,da1z/intellij-community,xfournet/intellij-community,da1z/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,allotria/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,da1z/intellij-community,ibinti/intellij-community,da1z/intellij-community,semonte/intellij-community
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.util.gotoByName; import com.intellij.concurrency.JobLauncher; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiCompiledElement; import com.intellij.psi.PsiElement; import com.intellij.psi.SmartPointerManager; import com.intellij.psi.SmartPsiElementPointer; import com.intellij.psi.codeStyle.MinusculeMatcher; import com.intellij.psi.codeStyle.NameUtil; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.proximity.PsiProximityComparator; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.FList; import com.intellij.util.indexing.FindSymbolParameters; import com.intellij.util.indexing.IdFilter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public class DefaultChooseByNameItemProvider implements ChooseByNameItemProvider { private static final Logger LOG = Logger.getInstance("#com.intellij.ide.util.gotoByName.ChooseByNameIdea"); private final SmartPsiElementPointer myContext; public DefaultChooseByNameItemProvider(@Nullable PsiElement context) { myContext = context == null ? null : SmartPointerManager.getInstance(context.getProject()).createSmartPsiElementPointer(context); } @Override public boolean filterElements(@NotNull final ChooseByNameBase base, @NotNull final String pattern, boolean everywhere, @NotNull final ProgressIndicator indicator, @NotNull final Processor<Object> consumer) { if (base.myProject != null) base.myProject.putUserData(ChooseByNamePopup.CURRENT_SEARCH_PATTERN, pattern); String namePattern = getNamePattern(base, pattern); String qualifierPattern = getQualifierPattern(base, pattern); if (removeModelSpecificMarkup(base.getModel(), namePattern).isEmpty() && !base.canShowListForEmptyPattern()) return true; final ChooseByNameModel model = base.getModel(); String matchingPattern = convertToMatchingPattern(base, namePattern); if (matchingPattern == null) return true; List<MatchResult> namesList = new ArrayList<>(); final CollectConsumer<MatchResult> collect = new SynchronizedCollectConsumer<>(namesList); long started; if (model instanceof ChooseByNameModelEx) { indicator.checkCanceled(); started = System.currentTimeMillis(); final MinusculeMatcher matcher = buildPatternMatcher(matchingPattern, NameUtil.MatchingCaseSensitivity.NONE); ((ChooseByNameModelEx)model).processNames(sequence -> { indicator.checkCanceled(); MatchResult result = matches(base, pattern, matcher, sequence); if (result != null) { collect.consume(result); return true; } return false; }, everywhere); if (LOG.isDebugEnabled()) { LOG.debug("loaded + matched:"+ (System.currentTimeMillis() - started)+ "," + collect.getResult().size()); } } else { String[] names = base.getNames(everywhere); started = System.currentTimeMillis(); processNamesByPattern(base, names, matchingPattern, indicator, collect); if (LOG.isDebugEnabled()) { LOG.debug("matched:"+ (System.currentTimeMillis() - started)+ "," + names.length); } } indicator.checkCanceled(); started = System.currentTimeMillis(); List<MatchResult> results = (List<MatchResult>)collect.getResult(); sortNamesList(namePattern, results); if (LOG.isDebugEnabled()) { LOG.debug("sorted:"+ (System.currentTimeMillis() - started) + ",results:" + results.size()); } indicator.checkCanceled(); List<Object> sameNameElements = new SmartList<>(); final Map<Object, MatchResult> qualifierMatchResults = ContainerUtil.newIdentityTroveMap(); Comparator<Object> weightComparator = new Comparator<Object>() { @SuppressWarnings("unchecked") Comparator<Object> modelComparator = model instanceof Comparator ? (Comparator<Object>)model : new PathProximityComparator(myContext == null ? null :myContext.getElement()); @Override public int compare(Object o1, Object o2) { int result = modelComparator.compare(o1, o2); return result != 0 ? result : qualifierMatchResults.get(o1).compareTo(qualifierMatchResults.get(o2)); } }; List<Object> qualifierMiddleMatched = new ArrayList<>(); List<Pair<String, MinusculeMatcher>> patternsAndMatchers = getPatternsAndMatchers(qualifierPattern, base); boolean sortedByMatchingDegree = !(base.getModel() instanceof CustomMatcherModel); IdFilter idFilter = null; if (model instanceof ContributorsBasedGotoByModel) { idFilter = ((ContributorsBasedGotoByModel)model).getIdFilter(everywhere); } GlobalSearchScope searchScope = FindSymbolParameters.searchScopeFor(base.myProject, everywhere); FindSymbolParameters parameters = new FindSymbolParameters(pattern, namePattern, searchScope, idFilter); boolean afterStartMatch = false; for (MatchResult result : namesList) { indicator.checkCanceled(); String name = result.elementName; boolean needSeparator = sortedByMatchingDegree && !result.startMatch && afterStartMatch; // use interruptible call if possible Object[] elements = model instanceof ContributorsBasedGotoByModel ? ((ContributorsBasedGotoByModel)model).getElementsByName(name, parameters, indicator) : model.getElementsByName(name, everywhere, namePattern); if (elements.length > 1) { sameNameElements.clear(); qualifierMatchResults.clear(); for (final Object element : elements) { indicator.checkCanceled(); MatchResult qualifierResult = matchQualifier(element, base, patternsAndMatchers); if (qualifierResult != null) { sameNameElements.add(element); qualifierMatchResults.put(element, qualifierResult); } } Collections.sort(sameNameElements, weightComparator); for (Object element : sameNameElements) { if (!qualifierMatchResults.get(element).startMatch) { qualifierMiddleMatched.add(element); continue; } if (needSeparator && !startMiddleMatchVariants(qualifierMiddleMatched, consumer)) return false; if (!consumer.process(element)) return false; needSeparator = false; afterStartMatch = result.startMatch; } } else if (elements.length == 1 && matchQualifier(elements[0], base, patternsAndMatchers) != null) { if (needSeparator && !startMiddleMatchVariants(qualifierMiddleMatched, consumer)) return false; if (!consumer.process(elements[0])) return false; afterStartMatch = result.startMatch; } } return ContainerUtil.process(qualifierMiddleMatched, consumer); } private static boolean startMiddleMatchVariants(@NotNull List<Object> qualifierMiddleMatched, @NotNull Processor<Object> consumer) { if (!consumer.process(ChooseByNameBase.NON_PREFIX_SEPARATOR)) return false; if (!ContainerUtil.process(qualifierMiddleMatched, consumer)) return false; qualifierMiddleMatched.clear(); return true; } private static void sortNamesList(@NotNull String namePattern, @NotNull List<MatchResult> namesList) { Collections.sort(namesList, (mr1, mr2) -> { boolean exactPrefix1 = namePattern.equalsIgnoreCase(mr1.elementName); boolean exactPrefix2 = namePattern.equalsIgnoreCase(mr2.elementName); if (exactPrefix1 != exactPrefix2) return exactPrefix1 ? -1 : 1; return mr1.compareTo(mr2); }); } @NotNull private static String getQualifierPattern(@NotNull ChooseByNameBase base, @NotNull String pattern) { pattern = base.transformPattern(pattern); final String[] separators = base.getModel().getSeparators(); int lastSeparatorOccurrence = 0; for (String separator : separators) { int idx = pattern.lastIndexOf(separator); if (idx == pattern.length() - 1) { // avoid empty name idx = pattern.lastIndexOf(separator, idx - 1); } lastSeparatorOccurrence = Math.max(lastSeparatorOccurrence, idx); } return pattern.substring(0, lastSeparatorOccurrence); } @NotNull private static String getNamePattern(@NotNull ChooseByNameBase base, String pattern) { String transformedPattern = base.transformPattern(pattern); return getNamePattern(base.getModel(), transformedPattern); } public static String getNamePattern(ChooseByNameModel model, String pattern) { final String[] separators = model.getSeparators(); int lastSeparatorOccurrence = 0; for (String separator : separators) { int idx = pattern.lastIndexOf(separator); if (idx == pattern.length() - 1) { // avoid empty name idx = pattern.lastIndexOf(separator, idx - 1); } lastSeparatorOccurrence = Math.max(lastSeparatorOccurrence, idx == -1 ? idx : idx + separator.length()); } return pattern.substring(lastSeparatorOccurrence); } @NotNull private static List<String> split(@NotNull String s, @NotNull ChooseByNameBase base) { List<String> answer = new ArrayList<>(); for (String token : StringUtil.tokenize(s, StringUtil.join(base.getModel().getSeparators(), ""))) { if (!token.isEmpty()) { answer.add(token); } } return answer.isEmpty() ? Collections.singletonList(s) : answer; } private static MatchResult matchQualifier(@NotNull Object element, @NotNull final ChooseByNameBase base, @NotNull List<Pair<String, MinusculeMatcher>> patternsAndMatchers) { final String name = base.getModel().getFullName(element); if (name == null) return null; final List<String> suspects = split(name, base); int matchingDegree = 0; int matchPosition = 0; boolean startMatch = true; patterns: for (Pair<String, MinusculeMatcher> patternAndMatcher : patternsAndMatchers) { final String pattern = patternAndMatcher.first; final MinusculeMatcher matcher = patternAndMatcher.second; if (!pattern.isEmpty()) { for (int j = matchPosition; j < suspects.size() - 1; j++) { String suspect = suspects.get(j); MatchResult suspectMatch = matches(base, pattern, matcher, suspect); if (suspectMatch != null) { matchingDegree += suspectMatch.matchingDegree; startMatch &= suspectMatch.startMatch; matchPosition = j + 1; continue patterns; } // pattern "foo/index" should prefer "bar/foo/index.html" to "foo/bar/index.html" // hence penalize every non-adjacent match matchingDegree -= (j + 1)*(j + 1); } return null; } } // penalize last skipped path parts for (int j = matchPosition; j < suspects.size() - 1; j++) { matchingDegree -= (j + 1)*(j + 1); } return new MatchResult(name, matchingDegree, startMatch); } @NotNull private static List<Pair<String, MinusculeMatcher>> getPatternsAndMatchers(@NotNull String qualifierPattern, @NotNull final ChooseByNameBase base) { return ContainerUtil.map2List(split(qualifierPattern, base), s -> { String namePattern = addSearchAnywherePatternDecorationIfNeeded(base, getNamePattern(base, s)); return Pair.create(namePattern, buildPatternMatcher(namePattern, NameUtil.MatchingCaseSensitivity.NONE)); }); } @NotNull @Override public List<String> filterNames(@NotNull ChooseByNameBase base, @NotNull String[] names, @NotNull String pattern) { pattern = convertToMatchingPattern(base, pattern); if (pattern == null) return Collections.emptyList(); final List<String> filtered = new ArrayList<>(); processNamesByPattern(base, names, pattern, ProgressIndicatorProvider.getGlobalProgressIndicator(), result -> { synchronized (filtered) { filtered.add(result.elementName); } }); synchronized (filtered) { return filtered; } } private static void processNamesByPattern(@NotNull final ChooseByNameBase base, @NotNull final String[] names, @NotNull final String pattern, final ProgressIndicator indicator, @NotNull final Consumer<MatchResult> consumer) { final MinusculeMatcher matcher = buildPatternMatcher(pattern, NameUtil.MatchingCaseSensitivity.NONE); Processor<String> processor = name -> { ProgressManager.checkCanceled(); MatchResult result = matches(base, pattern, matcher, name); if (result != null) { consumer.consume(result); } return true; }; if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(Arrays.asList(names), indicator, false, true, processor)) { throw new ProcessCanceledException(); } } @Nullable private static String convertToMatchingPattern(@NotNull ChooseByNameBase base, @NotNull String pattern) { pattern = removeModelSpecificMarkup(base.getModel(), pattern); if (!base.canShowListForEmptyPattern() && pattern.isEmpty()) { return null; } return addSearchAnywherePatternDecorationIfNeeded(base, pattern); } @NotNull private static String addSearchAnywherePatternDecorationIfNeeded(@NotNull ChooseByNameBase base, @NotNull String pattern) { String trimmedPattern; if (base.isSearchInAnyPlace() && !(trimmedPattern = pattern.trim()).isEmpty() && trimmedPattern.length() > 1) { pattern = "*" + pattern; } return pattern; } @NotNull private static String removeModelSpecificMarkup(@NotNull ChooseByNameModel model, @NotNull String pattern) { if (model instanceof ContributorsBasedGotoByModel) { pattern = ((ContributorsBasedGotoByModel)model).removeModelSpecificMarkup(pattern); } return pattern; } @Nullable private static MatchResult matches(@NotNull ChooseByNameBase base, @NotNull String pattern, @NotNull MinusculeMatcher matcher, @Nullable String name) { if (name == null) { return null; } if (base.getModel() instanceof CustomMatcherModel) { try { return ((CustomMatcherModel)base.getModel()).matches(name, pattern) ? new MatchResult(name, 0, true) : null; } catch (Exception e) { LOG.info(e); return null; // no matches appears valid result for "bad" pattern } } FList<TextRange> fragments = matcher.matchingFragments(name); return fragments != null ? new MatchResult(name, matcher.matchingDegree(name, false, fragments), MinusculeMatcher.isStartMatch(fragments)) : null; } @NotNull private static MinusculeMatcher buildPatternMatcher(@NotNull String pattern, @NotNull NameUtil.MatchingCaseSensitivity caseSensitivity) { return NameUtil.buildMatcher(pattern, caseSensitivity); } private static class PathProximityComparator implements Comparator<Object> { @NotNull private final PsiProximityComparator myProximityComparator; private PathProximityComparator(@Nullable final PsiElement context) { myProximityComparator = new PsiProximityComparator(context); } private static boolean isCompiledWithoutSource(Object o) { return o instanceof PsiCompiledElement && ((PsiCompiledElement)o).getNavigationElement() == o; } @Override public int compare(final Object o1, final Object o2) { int rc = myProximityComparator.compare(o1, o2); if (rc != 0) return rc; int o1Weight = isCompiledWithoutSource(o1) ? 1 : 0; int o2Weight = isCompiledWithoutSource(o2) ? 1 : 0; return o1Weight - o2Weight; } } }
platform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultChooseByNameItemProvider.java
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.util.gotoByName; import com.intellij.concurrency.JobLauncher; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiCompiledElement; import com.intellij.psi.PsiElement; import com.intellij.psi.SmartPointerManager; import com.intellij.psi.SmartPsiElementPointer; import com.intellij.psi.codeStyle.MinusculeMatcher; import com.intellij.psi.codeStyle.NameUtil; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.proximity.PsiProximityComparator; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.FList; import com.intellij.util.indexing.FindSymbolParameters; import com.intellij.util.indexing.IdFilter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public class DefaultChooseByNameItemProvider implements ChooseByNameItemProvider { private static final Logger LOG = Logger.getInstance("#com.intellij.ide.util.gotoByName.ChooseByNameIdea"); private final SmartPsiElementPointer myContext; public DefaultChooseByNameItemProvider(@Nullable PsiElement context) { myContext = context == null ? null : SmartPointerManager.getInstance(context.getProject()).createSmartPsiElementPointer(context); } @Override public boolean filterElements(@NotNull final ChooseByNameBase base, @NotNull final String pattern, boolean everywhere, @NotNull final ProgressIndicator indicator, @NotNull final Processor<Object> consumer) { base.myProject.putUserData(ChooseByNamePopup.CURRENT_SEARCH_PATTERN, pattern); String namePattern = getNamePattern(base, pattern); String qualifierPattern = getQualifierPattern(base, pattern); if (removeModelSpecificMarkup(base.getModel(), namePattern).isEmpty() && !base.canShowListForEmptyPattern()) return true; final ChooseByNameModel model = base.getModel(); String matchingPattern = convertToMatchingPattern(base, namePattern); if (matchingPattern == null) return true; List<MatchResult> namesList = new ArrayList<>(); final CollectConsumer<MatchResult> collect = new SynchronizedCollectConsumer<>(namesList); long started; if (model instanceof ChooseByNameModelEx) { indicator.checkCanceled(); started = System.currentTimeMillis(); final MinusculeMatcher matcher = buildPatternMatcher(matchingPattern, NameUtil.MatchingCaseSensitivity.NONE); ((ChooseByNameModelEx)model).processNames(sequence -> { indicator.checkCanceled(); MatchResult result = matches(base, pattern, matcher, sequence); if (result != null) { collect.consume(result); return true; } return false; }, everywhere); if (LOG.isDebugEnabled()) { LOG.debug("loaded + matched:"+ (System.currentTimeMillis() - started)+ "," + collect.getResult().size()); } } else { String[] names = base.getNames(everywhere); started = System.currentTimeMillis(); processNamesByPattern(base, names, matchingPattern, indicator, collect); if (LOG.isDebugEnabled()) { LOG.debug("matched:"+ (System.currentTimeMillis() - started)+ "," + names.length); } } indicator.checkCanceled(); started = System.currentTimeMillis(); List<MatchResult> results = (List<MatchResult>)collect.getResult(); sortNamesList(namePattern, results); if (LOG.isDebugEnabled()) { LOG.debug("sorted:"+ (System.currentTimeMillis() - started) + ",results:" + results.size()); } indicator.checkCanceled(); List<Object> sameNameElements = new SmartList<>(); final Map<Object, MatchResult> qualifierMatchResults = ContainerUtil.newIdentityTroveMap(); Comparator<Object> weightComparator = new Comparator<Object>() { @SuppressWarnings("unchecked") Comparator<Object> modelComparator = model instanceof Comparator ? (Comparator<Object>)model : new PathProximityComparator(myContext == null ? null :myContext.getElement()); @Override public int compare(Object o1, Object o2) { int result = modelComparator.compare(o1, o2); return result != 0 ? result : qualifierMatchResults.get(o1).compareTo(qualifierMatchResults.get(o2)); } }; List<Object> qualifierMiddleMatched = new ArrayList<>(); List<Pair<String, MinusculeMatcher>> patternsAndMatchers = getPatternsAndMatchers(qualifierPattern, base); boolean sortedByMatchingDegree = !(base.getModel() instanceof CustomMatcherModel); IdFilter idFilter = null; if (model instanceof ContributorsBasedGotoByModel) { idFilter = ((ContributorsBasedGotoByModel)model).getIdFilter(everywhere); } GlobalSearchScope searchScope = FindSymbolParameters.searchScopeFor(base.myProject, everywhere); FindSymbolParameters parameters = new FindSymbolParameters(pattern, namePattern, searchScope, idFilter); boolean afterStartMatch = false; for (MatchResult result : namesList) { indicator.checkCanceled(); String name = result.elementName; boolean needSeparator = sortedByMatchingDegree && !result.startMatch && afterStartMatch; // use interruptible call if possible Object[] elements = model instanceof ContributorsBasedGotoByModel ? ((ContributorsBasedGotoByModel)model).getElementsByName(name, parameters, indicator) : model.getElementsByName(name, everywhere, namePattern); if (elements.length > 1) { sameNameElements.clear(); qualifierMatchResults.clear(); for (final Object element : elements) { indicator.checkCanceled(); MatchResult qualifierResult = matchQualifier(element, base, patternsAndMatchers); if (qualifierResult != null) { sameNameElements.add(element); qualifierMatchResults.put(element, qualifierResult); } } Collections.sort(sameNameElements, weightComparator); for (Object element : sameNameElements) { if (!qualifierMatchResults.get(element).startMatch) { qualifierMiddleMatched.add(element); continue; } if (needSeparator && !startMiddleMatchVariants(qualifierMiddleMatched, consumer)) return false; if (!consumer.process(element)) return false; needSeparator = false; afterStartMatch = result.startMatch; } } else if (elements.length == 1 && matchQualifier(elements[0], base, patternsAndMatchers) != null) { if (needSeparator && !startMiddleMatchVariants(qualifierMiddleMatched, consumer)) return false; if (!consumer.process(elements[0])) return false; afterStartMatch = result.startMatch; } } return ContainerUtil.process(qualifierMiddleMatched, consumer); } private static boolean startMiddleMatchVariants(@NotNull List<Object> qualifierMiddleMatched, @NotNull Processor<Object> consumer) { if (!consumer.process(ChooseByNameBase.NON_PREFIX_SEPARATOR)) return false; if (!ContainerUtil.process(qualifierMiddleMatched, consumer)) return false; qualifierMiddleMatched.clear(); return true; } private static void sortNamesList(@NotNull String namePattern, @NotNull List<MatchResult> namesList) { Collections.sort(namesList, (mr1, mr2) -> { boolean exactPrefix1 = namePattern.equalsIgnoreCase(mr1.elementName); boolean exactPrefix2 = namePattern.equalsIgnoreCase(mr2.elementName); if (exactPrefix1 != exactPrefix2) return exactPrefix1 ? -1 : 1; return mr1.compareTo(mr2); }); } @NotNull private static String getQualifierPattern(@NotNull ChooseByNameBase base, @NotNull String pattern) { pattern = base.transformPattern(pattern); final String[] separators = base.getModel().getSeparators(); int lastSeparatorOccurrence = 0; for (String separator : separators) { int idx = pattern.lastIndexOf(separator); if (idx == pattern.length() - 1) { // avoid empty name idx = pattern.lastIndexOf(separator, idx - 1); } lastSeparatorOccurrence = Math.max(lastSeparatorOccurrence, idx); } return pattern.substring(0, lastSeparatorOccurrence); } @NotNull private static String getNamePattern(@NotNull ChooseByNameBase base, String pattern) { String transformedPattern = base.transformPattern(pattern); return getNamePattern(base.getModel(), transformedPattern); } public static String getNamePattern(ChooseByNameModel model, String pattern) { final String[] separators = model.getSeparators(); int lastSeparatorOccurrence = 0; for (String separator : separators) { int idx = pattern.lastIndexOf(separator); if (idx == pattern.length() - 1) { // avoid empty name idx = pattern.lastIndexOf(separator, idx - 1); } lastSeparatorOccurrence = Math.max(lastSeparatorOccurrence, idx == -1 ? idx : idx + separator.length()); } return pattern.substring(lastSeparatorOccurrence); } @NotNull private static List<String> split(@NotNull String s, @NotNull ChooseByNameBase base) { List<String> answer = new ArrayList<>(); for (String token : StringUtil.tokenize(s, StringUtil.join(base.getModel().getSeparators(), ""))) { if (!token.isEmpty()) { answer.add(token); } } return answer.isEmpty() ? Collections.singletonList(s) : answer; } private static MatchResult matchQualifier(@NotNull Object element, @NotNull final ChooseByNameBase base, @NotNull List<Pair<String, MinusculeMatcher>> patternsAndMatchers) { final String name = base.getModel().getFullName(element); if (name == null) return null; final List<String> suspects = split(name, base); int matchingDegree = 0; int matchPosition = 0; boolean startMatch = true; patterns: for (Pair<String, MinusculeMatcher> patternAndMatcher : patternsAndMatchers) { final String pattern = patternAndMatcher.first; final MinusculeMatcher matcher = patternAndMatcher.second; if (!pattern.isEmpty()) { for (int j = matchPosition; j < suspects.size() - 1; j++) { String suspect = suspects.get(j); MatchResult suspectMatch = matches(base, pattern, matcher, suspect); if (suspectMatch != null) { matchingDegree += suspectMatch.matchingDegree; startMatch &= suspectMatch.startMatch; matchPosition = j + 1; continue patterns; } // pattern "foo/index" should prefer "bar/foo/index.html" to "foo/bar/index.html" // hence penalize every non-adjacent match matchingDegree -= (j + 1)*(j + 1); } return null; } } // penalize last skipped path parts for (int j = matchPosition; j < suspects.size() - 1; j++) { matchingDegree -= (j + 1)*(j + 1); } return new MatchResult(name, matchingDegree, startMatch); } @NotNull private static List<Pair<String, MinusculeMatcher>> getPatternsAndMatchers(@NotNull String qualifierPattern, @NotNull final ChooseByNameBase base) { return ContainerUtil.map2List(split(qualifierPattern, base), s -> { String namePattern = addSearchAnywherePatternDecorationIfNeeded(base, getNamePattern(base, s)); return Pair.create(namePattern, buildPatternMatcher(namePattern, NameUtil.MatchingCaseSensitivity.NONE)); }); } @NotNull @Override public List<String> filterNames(@NotNull ChooseByNameBase base, @NotNull String[] names, @NotNull String pattern) { pattern = convertToMatchingPattern(base, pattern); if (pattern == null) return Collections.emptyList(); final List<String> filtered = new ArrayList<>(); processNamesByPattern(base, names, pattern, ProgressIndicatorProvider.getGlobalProgressIndicator(), result -> { synchronized (filtered) { filtered.add(result.elementName); } }); synchronized (filtered) { return filtered; } } private static void processNamesByPattern(@NotNull final ChooseByNameBase base, @NotNull final String[] names, @NotNull final String pattern, final ProgressIndicator indicator, @NotNull final Consumer<MatchResult> consumer) { final MinusculeMatcher matcher = buildPatternMatcher(pattern, NameUtil.MatchingCaseSensitivity.NONE); Processor<String> processor = name -> { ProgressManager.checkCanceled(); MatchResult result = matches(base, pattern, matcher, name); if (result != null) { consumer.consume(result); } return true; }; if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(Arrays.asList(names), indicator, false, true, processor)) { throw new ProcessCanceledException(); } } @Nullable private static String convertToMatchingPattern(@NotNull ChooseByNameBase base, @NotNull String pattern) { pattern = removeModelSpecificMarkup(base.getModel(), pattern); if (!base.canShowListForEmptyPattern() && pattern.isEmpty()) { return null; } return addSearchAnywherePatternDecorationIfNeeded(base, pattern); } @NotNull private static String addSearchAnywherePatternDecorationIfNeeded(@NotNull ChooseByNameBase base, @NotNull String pattern) { String trimmedPattern; if (base.isSearchInAnyPlace() && !(trimmedPattern = pattern.trim()).isEmpty() && trimmedPattern.length() > 1) { pattern = "*" + pattern; } return pattern; } @NotNull private static String removeModelSpecificMarkup(@NotNull ChooseByNameModel model, @NotNull String pattern) { if (model instanceof ContributorsBasedGotoByModel) { pattern = ((ContributorsBasedGotoByModel)model).removeModelSpecificMarkup(pattern); } return pattern; } @Nullable private static MatchResult matches(@NotNull ChooseByNameBase base, @NotNull String pattern, @NotNull MinusculeMatcher matcher, @Nullable String name) { if (name == null) { return null; } if (base.getModel() instanceof CustomMatcherModel) { try { return ((CustomMatcherModel)base.getModel()).matches(name, pattern) ? new MatchResult(name, 0, true) : null; } catch (Exception e) { LOG.info(e); return null; // no matches appears valid result for "bad" pattern } } FList<TextRange> fragments = matcher.matchingFragments(name); return fragments != null ? new MatchResult(name, matcher.matchingDegree(name, false, fragments), MinusculeMatcher.isStartMatch(fragments)) : null; } @NotNull private static MinusculeMatcher buildPatternMatcher(@NotNull String pattern, @NotNull NameUtil.MatchingCaseSensitivity caseSensitivity) { return NameUtil.buildMatcher(pattern, caseSensitivity); } private static class PathProximityComparator implements Comparator<Object> { @NotNull private final PsiProximityComparator myProximityComparator; private PathProximityComparator(@Nullable final PsiElement context) { myProximityComparator = new PsiProximityComparator(context); } private static boolean isCompiledWithoutSource(Object o) { return o instanceof PsiCompiledElement && ((PsiCompiledElement)o).getNavigationElement() == o; } @Override public int compare(final Object o1, final Object o2) { int rc = myProximityComparator.compare(o1, o2); if (rc != 0) return rc; int o1Weight = isCompiledWithoutSource(o1) ? 1 : 0; int o2Weight = isCompiledWithoutSource(o2) ? 1 : 0; return o1Weight - o2Weight; } } }
IDEA-167624 Find Action popup can not be closed on Welcome Screen; NPE at com.intellij.ide.util.gotoByName.ChooseByNamePopup.dispose
platform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultChooseByNameItemProvider.java
IDEA-167624 Find Action popup can not be closed on Welcome Screen; NPE at com.intellij.ide.util.gotoByName.ChooseByNamePopup.dispose
<ide><path>latform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultChooseByNameItemProvider.java <ide> boolean everywhere, <ide> @NotNull final ProgressIndicator indicator, <ide> @NotNull final Processor<Object> consumer) { <del> base.myProject.putUserData(ChooseByNamePopup.CURRENT_SEARCH_PATTERN, pattern); <add> if (base.myProject != null) base.myProject.putUserData(ChooseByNamePopup.CURRENT_SEARCH_PATTERN, pattern); <ide> <ide> String namePattern = getNamePattern(base, pattern); <ide> String qualifierPattern = getQualifierPattern(base, pattern);
Java
apache-2.0
345044f420ce3a5ce64c84d753846f220f4544b5
0
cityzendata/warp10-platform,hbs/warp10-platform,hbs/warp10-platform,cityzendata/warp10-platform,StevenLeRoux/warp10-platform,hbs/warp10-platform,cityzendata/warp10-platform,StevenLeRoux/warp10-platform,hbs/warp10-platform,cityzendata/warp10-platform,StevenLeRoux/warp10-platform,StevenLeRoux/warp10-platform
package io.warp10.hadoop; import io.warp10.continuum.store.Constants; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import com.fasterxml.sort.SortConfig; import com.fasterxml.sort.std.TextFileSorter; import org.apache.hadoop.mapreduce.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Warp10InputFormat extends InputFormat<Text, BytesWritable> { private static final Logger LOG = LoggerFactory.getLogger(Warp10InputFormat.class); /** * URL of split endpoint */ public static final String PROPERTY_WARP10_SPLITS_ENDPOINT = "warp10.splits.endpoint"; /** * List of fallback fetchers */ public static final String PROPERTY_WARP10_FETCHER_FALLBACKS = "warp10.fetcher.fallbacks"; /** * Protocol to use when contacting the fetcher (http or https), defaults to http */ public static final String PROPERTY_WARP10_FETCHER_PROTOCOL = "warp10.fetcher.protocol"; public static final String DEFAULT_WARP10_FETCHER_PROTOCOL = "http"; /** * Port to use when contacting the fetcher, defaults to 8881 */ public static final String PROPERTY_WARP10_FETCHER_PORT = "warp10.fetcher.port"; public static final String DEFAULT_WARP10_FETCHER_PORT = "8881"; /** * URL Path of the fetcher, defaults to "/api/v0/sfetch" */ public static final String PROPERTY_WARP10_FETCHER_PATH = "warp10.fetcher.path"; public static final String DEFAULT_WARP10_FETCHER_PATH = Constants.API_ENDPOINT_SFETCH; /** * GTS Selector */ public static final String PROPERTY_WARP10_SPLITS_SELECTOR = "warp10.splits.selector"; /** * Token to use for selecting GTS */ public static final String PROPERTY_WARP10_SPLITS_TOKEN = "warp10.splits.token"; /** * Connection timeout to the splits and sfetch endpoints, defaults to 2000 ms */ public static final String PROPERTY_WARP10_HTTP_CONNECT_TIMEOUT = "warp10.http.connect.timeout"; public static final String DEFAULT_WARP10_HTTP_CONNECT_TIMEOUT = "2000"; /** * Now parameter */ public static final String PROPERTY_WARP10_FETCH_NOW = "warp10.fetch.now"; /** * Timespan parameter */ public static final String PROPERTY_WARP10_FETCH_TIMESPAN = "warp10.fetch.timespan"; /** * Maximum number of splits to combined into a single split */ public static final String PROPERTY_WARP10_MAX_COMBINED_SPLITS = "warp10.max.combined.splits"; /** * Maximum number of splits we wish to produce */ public static final String PROPERTY_WARP10_MAX_SPLITS = "warp10.max.splits"; /** * Default Now HTTP Header */ public static final String HTTP_HEADER_NOW_HEADER_DEFAULT = "X-Warp10-Now"; /** * Default Timespan HTTP Header */ public static final String HTTP_HEADER_TIMESPAN_HEADER_DEFAULT = "X-Warp10-Timespan"; public Warp10InputFormat() { } @Override public List<InputSplit> getSplits(JobContext context) throws IOException { List<String> fallbacks = new ArrayList<>(); if (null != context.getConfiguration().get(PROPERTY_WARP10_FETCHER_FALLBACKS)) { String[] servers = context.getConfiguration().get(PROPERTY_WARP10_FETCHER_FALLBACKS).split(","); for (String server: servers) { fallbacks.add(server); } } int connectTimeout = Integer.valueOf(context.getConfiguration().get(Warp10InputFormat.PROPERTY_WARP10_HTTP_CONNECT_TIMEOUT, Warp10InputFormat.DEFAULT_WARP10_HTTP_CONNECT_TIMEOUT)); // // Issue a call to the /splits endpoint to retrieve the individual splits // StringBuilder sb = new StringBuilder(); sb.append(context.getConfiguration().get(PROPERTY_WARP10_SPLITS_ENDPOINT)); sb.append("?"); sb.append(Constants.HTTP_PARAM_SELECTOR); sb.append("="); sb.append(URLEncoder.encode(context.getConfiguration().get(PROPERTY_WARP10_SPLITS_SELECTOR), "UTF-8")); sb.append("&"); sb.append(Constants.HTTP_PARAM_TOKEN); sb.append("="); sb.append(context.getConfiguration().get(PROPERTY_WARP10_SPLITS_TOKEN)); URL url = new URL(sb.toString()); LOG.info("Get splits from: " + url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(connectTimeout); conn.setDoInput(true); InputStream in = conn.getInputStream(); File tmpfile = File.createTempFile("Warp10InputFormat-", "-in"); tmpfile.deleteOnExit(); OutputStream out = new FileOutputStream(tmpfile); BufferedReader br = new BufferedReader(new InputStreamReader(in)); PrintWriter pw = new PrintWriter(out); int count = 0; Map<String,AtomicInteger> perServer = new HashMap<String,AtomicInteger>(); while(true) { String line = br.readLine(); if (null == line) { break; } // Count the total number of splits count++; // Count the number of splits per RS String server = line.substring(0, line.indexOf(' ')); AtomicInteger scount = perServer.get(server); if (null == scount) { scount = new AtomicInteger(0); perServer.put(server, scount); } scount.addAndGet(1); pw.println(line); } pw.flush(); out.close(); br.close(); in.close(); conn.disconnect(); TextFileSorter sorter = new TextFileSorter(new SortConfig().withMaxMemoryUsage(64000000L)); File outfile = File.createTempFile("Warp10InputFormat-", "-out"); outfile.deleteOnExit(); in = new FileInputStream(tmpfile); out = new FileOutputStream(outfile); sorter.sort(in, out); out.close(); in.close(); // // Do a naive split generation, using the RegionServer as the ideal fetcher. We will need // to adapt this later so we ventilate the splits on all fetchers if we notice that a single // fetcher gets pounded too much // // Compute the maximum number of splits which can be combined given the number of servers (RS) int avgsplitcount = (int) Math.ceil((double) count / perServer.size()); if (null != context.getConfiguration().get(PROPERTY_WARP10_MAX_SPLITS)) { int maxsplitavg = (int) Math.ceil((double) count / Integer.parseInt(context.getConfiguration().get(PROPERTY_WARP10_MAX_SPLITS))); avgsplitcount = maxsplitavg; } if (null != context.getConfiguration().get(PROPERTY_WARP10_MAX_COMBINED_SPLITS)) { int maxcombined = Integer.parseInt(context.getConfiguration().get(PROPERTY_WARP10_MAX_COMBINED_SPLITS)); if (maxcombined < avgsplitcount) { avgsplitcount = maxcombined; } } List<InputSplit> splits = new ArrayList<>(); br = new BufferedReader(new FileReader(outfile)); Warp10InputSplit split = new Warp10InputSplit(); String lastserver = null; int subsplits = 0; while(true) { String line = br.readLine(); if (null == line) { break; } String[] tokens = line.split("\\s+"); // If the server changed or we've reached the maximum split size, flush the current split. if (null != lastserver && !lastserver.equals(tokens[0]) || avgsplitcount == subsplits) { // Add fallback fetchers, shuffle them first Collections.shuffle(fallbacks); for (String fallback: fallbacks) { split.addFetcher(fallback); } splits.add(split.build()); split = new Warp10InputSplit(); subsplits = 0; } subsplits++; split.addEntry(tokens[0], tokens[2]); } br.close(); if (subsplits > 0) { // Add fallback fetchers, shuffle them first Collections.shuffle(fallbacks); for (String fallback: fallbacks) { split.addFetcher(fallback); } splits.add(split.build()); } return splits; // // // // We know we have 'count' splits to combine and we know how many splits are hosted on each // // server // // // // // Compute the average number of splits per combined split // int avgsplitcount = (int) Math.ceil((double) count / numSplits); // // // Compute the average number of splits per server // int avgsplitpersrv = (int) Math.ceil((double) count / perServer.size()); // // // // // Determine the number of ideal (i.e. associated with the right server) combined splits // // per server // // // // Map<String,AtomicInteger> idealcount = new HashMap<String,AtomicInteger>(); // // for (Entry<String,AtomicInteger> entry: perServer.entrySet()) { // idealcount.put(entry.getKey(), new AtomicInteger(Math.min((int) Math.ceil(entry.getValue().doubleValue() / avgsplitcount), avgsplitpersrv))); // } // // // // // Compute the number of available slots per server after the maximum ideal combined splits // // have been allocated // // // // Map<String,AtomicInteger> freeslots = new HashMap<String,AtomicInteger>(); // // for (Entry<String,AtomicInteger> entry: perServer.entrySet()) { // if (entry.getValue().get() < avgsplitpersrv) { // freeslots.put(entry.getKey(), new AtomicInteger(avgsplitpersrv - entry.getValue().get())); // } // } // // // // // Generate splits // // We know the input file is sorted by server then region // // // // br = new BufferedReader(new FileReader(outfile)); // // Warp10InputSplit split = null; // String lastsrv = null; // int subsplits = 0; // // List<Warp10InputSplit> splits = new ArrayList<Warp10InputSplit>(); // // while(true) { // String line = br.readLine(); // // if (null == line) { // break; // } // // // Split line into tokens // String[] tokens = line.split("\\s+"); // // // If the srv changed, flush the split // if (null != lastsrv && lastsrv != tokens[0]) { // splits.add(split); // split = null; // } // // // if (null == splitsrv) { // splitsrv = tokens[0]; // // Check if 'splitsrv' can host more splits // if (idealcount.get(splitsrv)) // } // // Emit current split if it is full // // if (avgsplitcount == subsplits) { // // } // } // // System.out.println("NSPLITS=" + count); // // System.out.println("AVG=" + avgsplit); // System.out.println(perServer); // return null; } @Override public RecordReader<Text, BytesWritable> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException { if (!(split instanceof Warp10InputSplit)) { throw new IOException("Invalid split type."); } return new Warp10RecordReader(); } }
warp10/src/main/java/io/warp10/hadoop/Warp10InputFormat.java
package io.warp10.hadoop; import io.warp10.continuum.store.Constants; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import com.fasterxml.sort.SortConfig; import com.fasterxml.sort.std.TextFileSorter; import org.apache.hadoop.mapreduce.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Warp10InputFormat extends InputFormat<Text, BytesWritable> { private static final Logger LOG = LoggerFactory.getLogger(Warp10InputFormat.class); /** * URL of split endpoint */ public static final String PROPERTY_WARP10_SPLITS_ENDPOINT = "warp10.splits.endpoint"; /** * List of fallback fetchers */ public static final String PROPERTY_WARP10_FETCHER_FALLBACKS = "warp10.fetcher.fallbacks"; /** * Protocol to use when contacting the fetcher (http or https), defaults to http */ public static final String PROPERTY_WARP10_FETCHER_PROTOCOL = "warp10.fetcher.protocol"; public static final String DEFAULT_WARP10_FETCHER_PROTOCOL = "http"; /** * Port to use when contacting the fetcher, defaults to 8881 */ public static final String PROPERTY_WARP10_FETCHER_PORT = "warp10.fetcher.port"; public static final String DEFAULT_WARP10_FETCHER_PORT = "8881"; /** * URL Path of the fetcher, defaults to "/api/v0/sfetch" */ public static final String PROPERTY_WARP10_FETCHER_PATH = "warp10.fetcher.path"; public static final String DEFAULT_WARP10_FETCHER_PATH = Constants.API_ENDPOINT_SFETCH; /** * GTS Selector */ public static final String PROPERTY_WARP10_SPLITS_SELECTOR = "warp10.splits.selector"; /** * Token to use for selecting GTS */ public static final String PROPERTY_WARP10_SPLITS_TOKEN = "warp10.splits.token"; /** * Connection timeout to the splits and sfetch endpoints, defaults to 2000 ms */ public static final String PROPERTY_WARP10_HTTP_CONNECT_TIMEOUT = "warp10.http.connect.timeout"; public static final String DEFAULT_WARP10_HTTP_CONNECT_TIMEOUT = "2000"; /** * Now parameter */ public static final String PROPERTY_WARP10_FETCH_NOW = "warp10.fetch.now"; /** * Timespan parameter */ public static final String PROPERTY_WARP10_FETCH_TIMESPAN = "warp10.fetch.timespan"; /** * Default Now HTTP Header */ public static final String HTTP_HEADER_NOW_HEADER_DEFAULT = "X-Warp10-Now"; /** * Default Timespan HTTP Header */ public static final String HTTP_HEADER_TIMESPAN_HEADER_DEFAULT = "X-Warp10-Timespan"; public Warp10InputFormat() { } @Override public List<InputSplit> getSplits(JobContext context) throws IOException { List<String> fallbacks = new ArrayList<>(); if (null != context.getConfiguration().get(PROPERTY_WARP10_FETCHER_FALLBACKS)) { String[] servers = context.getConfiguration().get(PROPERTY_WARP10_FETCHER_FALLBACKS).split(","); for (String server: servers) { fallbacks.add(server); } } int connectTimeout = Integer.valueOf(context.getConfiguration().get(Warp10InputFormat.PROPERTY_WARP10_HTTP_CONNECT_TIMEOUT, Warp10InputFormat.DEFAULT_WARP10_HTTP_CONNECT_TIMEOUT)); // // Issue a call to the /splits endpoint to retrieve the individual splits // StringBuilder sb = new StringBuilder(); sb.append(context.getConfiguration().get(PROPERTY_WARP10_SPLITS_ENDPOINT)); sb.append("?"); sb.append(Constants.HTTP_PARAM_SELECTOR); sb.append("="); sb.append(URLEncoder.encode(context.getConfiguration().get(PROPERTY_WARP10_SPLITS_SELECTOR), "UTF-8")); sb.append("&"); sb.append(Constants.HTTP_PARAM_TOKEN); sb.append("="); sb.append(context.getConfiguration().get(PROPERTY_WARP10_SPLITS_TOKEN)); URL url = new URL(sb.toString()); LOG.info("Get splits from: " + url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(connectTimeout); conn.setDoInput(true); InputStream in = conn.getInputStream(); File tmpfile = File.createTempFile("Warp10InputFormat-", "-in"); tmpfile.deleteOnExit(); OutputStream out = new FileOutputStream(tmpfile); BufferedReader br = new BufferedReader(new InputStreamReader(in)); PrintWriter pw = new PrintWriter(out); int count = 0; Map<String,AtomicInteger> perServer = new HashMap<String,AtomicInteger>(); while(true) { String line = br.readLine(); if (null == line) { break; } // Count the total number of splits count++; // Count the number of splits per RS String server = line.substring(0, line.indexOf(' ')); AtomicInteger scount = perServer.get(server); if (null == scount) { scount = new AtomicInteger(0); perServer.put(server, scount); } scount.addAndGet(1); pw.println(line); } pw.flush(); out.close(); br.close(); in.close(); conn.disconnect(); TextFileSorter sorter = new TextFileSorter(new SortConfig().withMaxMemoryUsage(64000000L)); File outfile = File.createTempFile("Warp10InputFormat-", "-out"); outfile.deleteOnExit(); in = new FileInputStream(tmpfile); out = new FileOutputStream(outfile); sorter.sort(in, out); out.close(); in.close(); // // Do a naive split generation, using the RegionServer as the ideal fetcher. We will need // to adapt this later so we ventilate the splits on all fetchers if we notice that a single // fetcher gets pounded too much // // Compute the average number of splits per combined split int avgsplitcount = (int) Math.ceil((double) count / fallbacks.size()); List<InputSplit> splits = new ArrayList<>(); br = new BufferedReader(new FileReader(outfile)); Warp10InputSplit split = new Warp10InputSplit(); String lastserver = null; int subsplits = 0; while(true) { String line = br.readLine(); if (null == line) { break; } String[] tokens = line.split("\\s+"); // If the server changed or we've reached the maximum split size, flush the current split. if (null != lastserver && !lastserver.equals(tokens[0]) || avgsplitcount == subsplits) { // Add fallback fetchers, shuffle them first Collections.shuffle(fallbacks); for (String fallback: fallbacks) { split.addFetcher(fallback); } splits.add(split.build()); split = new Warp10InputSplit(); subsplits = 0; } subsplits++; split.addEntry(tokens[0], tokens[2]); } br.close(); if (subsplits > 0) { // Add fallback fetchers, shuffle them first Collections.shuffle(fallbacks); for (String fallback: fallbacks) { split.addFetcher(fallback); } splits.add(split.build()); } return splits; // // // // We know we have 'count' splits to combine and we know how many splits are hosted on each // // server // // // // // Compute the average number of splits per combined split // int avgsplitcount = (int) Math.ceil((double) count / numSplits); // // // Compute the average number of splits per server // int avgsplitpersrv = (int) Math.ceil((double) count / perServer.size()); // // // // // Determine the number of ideal (i.e. associated with the right server) combined splits // // per server // // // // Map<String,AtomicInteger> idealcount = new HashMap<String,AtomicInteger>(); // // for (Entry<String,AtomicInteger> entry: perServer.entrySet()) { // idealcount.put(entry.getKey(), new AtomicInteger(Math.min((int) Math.ceil(entry.getValue().doubleValue() / avgsplitcount), avgsplitpersrv))); // } // // // // // Compute the number of available slots per server after the maximum ideal combined splits // // have been allocated // // // // Map<String,AtomicInteger> freeslots = new HashMap<String,AtomicInteger>(); // // for (Entry<String,AtomicInteger> entry: perServer.entrySet()) { // if (entry.getValue().get() < avgsplitpersrv) { // freeslots.put(entry.getKey(), new AtomicInteger(avgsplitpersrv - entry.getValue().get())); // } // } // // // // // Generate splits // // We know the input file is sorted by server then region // // // // br = new BufferedReader(new FileReader(outfile)); // // Warp10InputSplit split = null; // String lastsrv = null; // int subsplits = 0; // // List<Warp10InputSplit> splits = new ArrayList<Warp10InputSplit>(); // // while(true) { // String line = br.readLine(); // // if (null == line) { // break; // } // // // Split line into tokens // String[] tokens = line.split("\\s+"); // // // If the srv changed, flush the split // if (null != lastsrv && lastsrv != tokens[0]) { // splits.add(split); // split = null; // } // // // if (null == splitsrv) { // splitsrv = tokens[0]; // // Check if 'splitsrv' can host more splits // if (idealcount.get(splitsrv)) // } // // Emit current split if it is full // // if (avgsplitcount == subsplits) { // // } // } // // System.out.println("NSPLITS=" + count); // // System.out.println("AVG=" + avgsplit); // System.out.println(perServer); // return null; } @Override public RecordReader<Text, BytesWritable> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException { if (!(split instanceof Warp10InputSplit)) { throw new IOException("Invalid split type."); } return new Warp10RecordReader(); } }
Added support for controlling number of splits
warp10/src/main/java/io/warp10/hadoop/Warp10InputFormat.java
Added support for controlling number of splits
<ide><path>arp10/src/main/java/io/warp10/hadoop/Warp10InputFormat.java <ide> public static final String PROPERTY_WARP10_FETCH_TIMESPAN = "warp10.fetch.timespan"; <ide> <ide> /** <add> * Maximum number of splits to combined into a single split <add> */ <add> public static final String PROPERTY_WARP10_MAX_COMBINED_SPLITS = "warp10.max.combined.splits"; <add> <add> /** <add> * Maximum number of splits we wish to produce <add> */ <add> public static final String PROPERTY_WARP10_MAX_SPLITS = "warp10.max.splits"; <add> <add> /** <ide> * Default Now HTTP Header <ide> */ <ide> public static final String HTTP_HEADER_NOW_HEADER_DEFAULT = "X-Warp10-Now"; <ide> // fetcher gets pounded too much <ide> // <ide> <del> // Compute the average number of splits per combined split <del> int avgsplitcount = (int) Math.ceil((double) count / fallbacks.size()); <add> // Compute the maximum number of splits which can be combined given the number of servers (RS) <add> int avgsplitcount = (int) Math.ceil((double) count / perServer.size()); <add> <add> if (null != context.getConfiguration().get(PROPERTY_WARP10_MAX_SPLITS)) { <add> int maxsplitavg = (int) Math.ceil((double) count / Integer.parseInt(context.getConfiguration().get(PROPERTY_WARP10_MAX_SPLITS))); <add> <add> avgsplitcount = maxsplitavg; <add> } <add> <add> if (null != context.getConfiguration().get(PROPERTY_WARP10_MAX_COMBINED_SPLITS)) { <add> int maxcombined = Integer.parseInt(context.getConfiguration().get(PROPERTY_WARP10_MAX_COMBINED_SPLITS)); <add> <add> if (maxcombined < avgsplitcount) { <add> avgsplitcount = maxcombined; <add> } <add> } <ide> <ide> List<InputSplit> splits = new ArrayList<>(); <ide>
Java
apache-2.0
32f010d15a450a3c119719eef09dd1865c55bc8a
0
mohanaraosv/commons-validator,floscher/commons-validator,apache/commons-validator,mohanaraosv/commons-validator,apache/commons-validator,floscher/commons-validator,mohanaraosv/commons-validator,apache/commons-validator,floscher/commons-validator
/* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//validator/src/share/org/apache/commons/validator/Field.java,v 1.19 2003/06/12 01:04:11 dgraham Exp $ * $Revision: 1.19 $ * $Date: 2003/06/12 01:04:11 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.commons.validator; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.apache.commons.collections.FastHashMap; import org.apache.commons.validator.util.ValidatorUtils; /** * <p> * This contains the list of pluggable validators to run on a field and any message * information and variables to perform the validations and generate error * messages. Instances of this class are configured with a &lt;field&gt; xml element. * </p> * * @author David Winterfeldt * @author David Graham * @version $Revision: 1.19 $ $Date: 2003/06/12 01:04:11 $ * @see org.apache.commons.validator.Form */ public class Field implements Cloneable, Serializable { /** * This is the value that will be used as a key if the <code>Arg</code> * name field has no value. */ private static final String DEFAULT_ARG = "org.apache.commons.validator.Field.DEFAULT"; /** * This is the value that will be used as a key if the <code>Arg</code> * name field has no value. * @deprecated */ public static final String ARG_DEFAULT = DEFAULT_ARG; /** * This indicates an indexed property is being referenced. */ public static final String TOKEN_INDEXED = "[]"; protected static final String TOKEN_START = "${"; protected static final String TOKEN_END = "}"; protected static final String TOKEN_VAR = "var:"; protected String property = null; protected String indexedProperty = null; protected String indexedListProperty = null; protected String key = null; /** * A comma separated list of validator's this field depends on. */ protected String depends = null; protected int page = 0; protected int fieldOrder = 0; /** * @deprecated This is no longer used. */ protected FastHashMap hDependencies = new FastHashMap(); /** * Internal representation of this.depends String as a List. This List gets updated * whenever setDepends() gets called. This List is synchronized so a call to * setDepends() (which clears the List) won't interfere with a call to * isDependency(). */ private List dependencyList = Collections.synchronizedList(new ArrayList()); protected FastHashMap hVars = new FastHashMap(); protected FastHashMap hMsgs = new FastHashMap(); /** * Holds Maps of arguments. args[0] returns the Map for the first replacement * argument. */ protected Map[] args = new Map[10]; /** * @deprecated This variable is no longer used, use args instead. */ protected FastHashMap hArg0 = new FastHashMap(); /** * @deprecated This variable is no longer used, use args instead. */ protected FastHashMap hArg1 = new FastHashMap(); /** * @deprecated This variable is no longer used, use args instead. */ protected FastHashMap hArg2 = new FastHashMap(); /** * @deprecated This variable is no longer used, use args instead. */ protected FastHashMap hArg3 = new FastHashMap(); /** * Gets the page value that the Field is associated with for * validation. */ public int getPage() { return this.page; } /** * Sets the page value that the Field is associated with for * validation. */ public void setPage(int page) { this.page = page; } /** * Gets the position of the <code>Field</code> in the validation list. */ public int getFieldOrder() { return this.fieldOrder; } /** * Sets the position of the <code>Field</code> in the validation list. */ public void setFieldOrder(int fieldOrder) { this.fieldOrder = fieldOrder; } /** * Gets the property name of the field. */ public String getProperty() { return this.property; } /** * Sets the property name of the field. */ public void setProperty(String property) { this.property = property; } /** * Gets the indexed property name of the field. This * is the method name that can take an <code>int</code> as * a parameter for indexed property value retrieval. */ public String getIndexedProperty() { return this.indexedProperty; } /** * Sets the indexed property name of the field. */ public void setIndexedProperty(String indexedProperty) { this.indexedProperty = indexedProperty; } /** * Gets the indexed property name of the field. This * is the method name that will return an array or a * <code>Collection</code> used to retrieve the * list and then loop through the list performing the specified * validations. */ public String getIndexedListProperty() { return this.indexedListProperty; } /** * Sets the indexed property name of the field. */ public void setIndexedListProperty(String indexedListProperty) { this.indexedListProperty = indexedListProperty; } /** * Gets the validation rules for this field as a comma separated list. */ public String getDepends() { return this.depends; } /** * Sets the validation rules for this field as a comma separated list. */ public void setDepends(String depends) { this.depends = depends; this.dependencyList.clear(); StringTokenizer st = new StringTokenizer(depends, ","); while (st.hasMoreTokens()) { String depend = st.nextToken().trim(); if (depend != null && depend.length() > 0) { this.dependencyList.add(depend); } } } /** * Add a <code>Msg</code> to the <code>Field</code>. */ public void addMsg(Msg msg) { if (msg != null && msg.getKey() != null && msg.getKey().length() > 0 && msg.getName() != null && msg.getName().length() > 0) { hMsgs.put(msg.getName(), msg.getKey()); } } /** * Retrieve a message value. */ public String getMsg(String key) { return (String)hMsgs.get(key); } /** * Add an <code>Arg</code> to the replacement argument list. */ public void addArg(Arg arg) { // TODO this first if check can go away after arg0, etc. are removed from dtd if (arg == null || arg.getKey() == null || arg.getKey().length() == 0) { return; } this.ensureArgsCapacity(arg); Map argMap = (Map) this.args[arg.getPosition()]; if (argMap == null) { argMap = new HashMap(); this.args[arg.getPosition()] = argMap; } if (arg.getName() == null) { argMap.put(DEFAULT_ARG, arg); } else { argMap.put(arg.getName(), arg); } } /** * Ensures that the args array can hold the given arg. Resizes the array as * necessary. * @param arg Determine if the args array is long enough to store this arg's * position. */ private void ensureArgsCapacity(Arg arg) { if (arg.getPosition() >= this.args.length) { Map[] newArgs = new Map[arg.getPosition() + 1]; System.arraycopy(this.args, 0, newArgs, 0, this.args.length); this.args = newArgs; } } /** * Gets the default <code>Arg</code> object at the given position. * @return The default Arg or null if not found. */ public Arg getArg(int position) { return this.getArg(DEFAULT_ARG, position); } /** * Gets the default <code>Arg</code> object at the given position. If the key * finds a <code>null</code> value then the default value will try to be retrieved. * @param key The name the Arg is stored under. If not found, the default Arg for * the given position (if any) will be retrieved. * @param position The Arg number to find. * @return The Arg with the given name and position or null if not found. */ public Arg getArg(String key, int position) { if ((position >= this.args.length) || (this.args[position] == null)) { return null; } Arg arg = (Arg) args[position].get(key); // Didn't find default arg so exit, otherwise we would get into infinite recursion if ((arg == null) && key.equals(DEFAULT_ARG)) { return null; } return (arg == null) ? this.getArg(position) : arg; } /** * Add a <code>Arg</code> to the arg0 list. * @deprecated Use addArg(Arg) instead. */ public void addArg0(Arg arg) { arg.setPosition(0); this.addArg(arg); } /** * Gets the default arg0 <code>Arg</code> object. * @deprecated Use getArg(0) instead. */ public Arg getArg0() { return this.getArg(0); } /** * Gets the arg0 <code>Arg</code> object based on the key passed in. If the key * finds a <code>null</code> value then the default value will try to be retrieved. * @deprecated Use getArg(String, 0) instead. */ public Arg getArg0(String key) { return this.getArg(key, 0); } /** * Add a <code>Arg</code> to the arg1 list. * @deprecated Use addArg(Arg) instead. */ public void addArg1(Arg arg) { arg.setPosition(1); this.addArg(arg); } /** * Gets the default arg1 <code>Arg</code> object. * @deprecated Use getArg(1) instead. */ public Arg getArg1() { return this.getArg(1); } /** * Gets the arg1 <code>Arg</code> object based on the key passed in. If the key * finds a <code>null</code> value then the default value will try to be retrieved. * @deprecated Use getArg(String, 1) instead. */ public Arg getArg1(String key) { return this.getArg(key, 1); } /** * Add a <code>Arg</code> to the arg2 list. * @deprecated Use addArg(Arg) instead. */ public void addArg2(Arg arg) { arg.setPosition(2); this.addArg(arg); } /** * Gets the default arg2 <code>Arg</code> object. * @deprecated Use getArg(2) instead. */ public Arg getArg2() { return this.getArg(2); } /** * Gets the arg2 <code>Arg</code> object based on the key passed in. If the key * finds a <code>null</code> value then the default value will try to be retrieved. * @deprecated Use getArg(String, 2) instead. */ public Arg getArg2(String key) { return this.getArg(key, 2); } /** * Add a <code>Arg</code> to the arg3 list. * @deprecated Use addArg(Arg) instead. */ public void addArg3(Arg arg) { arg.setPosition(3); this.addArg(arg); } /** * Gets the default arg3 <code>Arg</code> object. * @deprecated Use getArg(3) instead. */ public Arg getArg3() { return this.getArg(3); } /** * Gets the arg3 <code>Arg</code> object based on the key passed in. If the key * finds a <code>null</code> value then the default value will try to be retrieved. * @deprecated Use getArg(String, 3) instead. */ public Arg getArg3(String key) { return this.getArg(key, 3); } /** * Add a <code>Var</code> to the <code>Field</code>. */ public void addVar(Var v) { this.hVars.put(v.getName(), v); } /** * Add a <code>Var</code>, based on the values passed in, to the * <code>Field</code>. * @deprecated Use addVar(String, String, String) instead. */ public void addVarParam(String name, String value, String jsType) { this.addVar(new Var(name, value, jsType)); } /** * Add a <code>Var</code>, based on the values passed in, to the * <code>Field</code>. */ public void addVar(String name, String value, String jsType) { this.addVar(new Var(name, value, jsType)); } /** * Retrieve a variable. */ public Var getVar(String mainKey) { return (Var) hVars.get(mainKey); } /** * Retrieve a variable's value. */ public String getVarValue(String mainKey) { String value = null; Object o = hVars.get(mainKey); if (o != null && o instanceof Var) { Var v = (Var) o; value = v.getValue(); } return value; } /** * The <code>Field</code>'s variables are returned as an * unmodifiable <code>Map</code>. */ public Map getVars() { return Collections.unmodifiableMap(hVars); } /** * Gets a unique key based on the property and indexedProperty fields. */ public String getKey() { if (this.key == null) { this.generateKey(); } return this.key; } /** * Sets a unique key for the field. This can be used to change * the key temporarily to have a unique key for an indexed field. */ public void setKey(String key) { this.key = key; } /** * If there is a value specified for the indexedProperty field then * <code>true</code> will be returned. Otherwise it will be <code>false</code>. */ public boolean isIndexed() { return ((indexedListProperty != null && indexedListProperty.length() > 0)); } /** * Generate correct <code>key</code> value. */ public void generateKey() { if (this.isIndexed()) { this.key = this.indexedListProperty + TOKEN_INDEXED + "." + this.property; } else { this.key = this.property; } } /** * Replace constants with values in fields and process the depends field * to create the dependency <code>Map</code>. * @deprecated This method is called by the framework. It will be made protected * in a future release. TODO */ public void process(Map globalConstants, Map constants) { this.hMsgs.setFast(false); this.hVars.setFast(true); this.generateKey(); // Process FormSet Constants for (Iterator i = constants.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); String key2 = TOKEN_START + key + TOKEN_END; String replaceValue = (String) constants.get(key); property = ValidatorUtils.replace(property, key2, replaceValue); processVars(key2, replaceValue); this.processMessageComponents(key2, replaceValue); } // Process Global Constants for (Iterator i = globalConstants.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); String key2 = TOKEN_START + key + TOKEN_END; String replaceValue = (String) globalConstants.get(key); property = ValidatorUtils.replace(property, key2, replaceValue); processVars(key2, replaceValue); this.processMessageComponents(key2, replaceValue); } // Process Var Constant Replacement for (Iterator i = hVars.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); String key2 = TOKEN_START + TOKEN_VAR + key + TOKEN_END; Var var = this.getVar(key); String replaceValue = var.getValue(); this.processMessageComponents(key2, replaceValue); } hMsgs.setFast(true); } /** * Replace the vars value with the key/value pairs passed in. */ private void processVars(String key, String replaceValue) { Iterator i = this.hVars.keySet().iterator(); while (i.hasNext()) { String varKey = (String) i.next(); Var var = this.getVar(varKey); var.setValue(ValidatorUtils.replace(var.getValue(), key, replaceValue)); } } /** * Replace the args key value with the key/value pairs passed in. * @deprecated This is an internal setup method that clients don't need to call. */ public void processMessageComponents(String key, String replaceValue) { this.internalProcessMessageComponents(key, replaceValue); } /** * Replace the args key value with the key/value pairs passed in. * TODO When processMessageComponents() is removed from the public API we * should rename this private method to "processMessageComponents". */ private void internalProcessMessageComponents(String key, String replaceValue) { String varKey = TOKEN_START + TOKEN_VAR; // Process Messages if (key != null && !key.startsWith(varKey)) { for (Iterator i = hMsgs.keySet().iterator(); i.hasNext();) { String msgKey = (String) i.next(); String value = this.getMsg(msgKey); hMsgs.put(msgKey, ValidatorUtils.replace(value, key, replaceValue)); } } this.processArg(key, replaceValue); } /** * Replace the arg <code>Collection</code> key value with the key/value pairs * passed in. */ private void processArg(String key, String replaceValue) { for (int i = 0; i < this.args.length; i++) { Map argMap = this.args[i]; if (argMap == null) { continue; } Iterator iter = argMap.values().iterator(); while (iter.hasNext()) { Arg arg = (Arg) iter.next(); if (arg != null) { arg.setKey( ValidatorUtils.replace(arg.getKey(), key, replaceValue)); } } } } /** * Checks if the validator is listed as a dependency. */ public boolean isDependency(String validatorName) { return this.dependencyList.contains(validatorName); } /** * Gets an unmodifiable <code>Set</code> of the dependencies. * @deprecated Use getDependencyList() instead. */ public Collection getDependencies() { return this.getDependencyList(); } /** * Gets an unmodifiable <code>List</code> of the dependencies in the same order * they were defined in parameter passed to the setDepends() method. */ public List getDependencyList() { return Collections.unmodifiableList(this.dependencyList); } /** * Creates and returns a copy of this object. */ public Object clone() { Field field = null; try { field = (Field) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e.toString()); } field.args = new Map[this.args.length]; for (int i = 0; i < this.args.length; i++) { if (this.args[i] == null) { continue; } Map argMap = new HashMap(this.args[i]); Iterator iter = argMap.keySet().iterator(); while (iter.hasNext()) { String validatorName = (String) iter.next(); Arg arg = (Arg) argMap.get(validatorName); argMap.put(validatorName, arg.clone()); } field.args[i] = argMap; } field.hVars = ValidatorUtils.copyFastHashMap(hVars); field.hMsgs = ValidatorUtils.copyFastHashMap(hMsgs); field.hArg0 = ValidatorUtils.copyFastHashMap(hArg0); field.hArg1 = ValidatorUtils.copyFastHashMap(hArg1); field.hArg2 = ValidatorUtils.copyFastHashMap(hArg2); field.hArg3 = ValidatorUtils.copyFastHashMap(hArg3); return field; } /** * Returns a string representation of the object. */ public String toString() { StringBuffer results = new StringBuffer(); results.append("\t\tkey = " + key + "\n"); results.append("\t\tproperty = " + property + "\n"); results.append("\t\tindexedProperty = " + indexedProperty + "\n"); results.append("\t\tindexedListProperty = " + indexedListProperty + "\n"); results.append("\t\tdepends = " + depends + "\n"); results.append("\t\tpage = " + page + "\n"); results.append("\t\tfieldOrder = " + fieldOrder + "\n"); if (hVars != null) { results.append("\t\tVars:\n"); for (Iterator i = hVars.keySet().iterator(); i.hasNext();) { Object key = i.next(); results.append("\t\t\t"); results.append(key); results.append("="); results.append(hVars.get(key)); results.append("\n"); } } return results.toString(); } }
src/share/org/apache/commons/validator/Field.java
/* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//validator/src/share/org/apache/commons/validator/Field.java,v 1.18 2003/06/08 06:03:16 dgraham Exp $ * $Revision: 1.18 $ * $Date: 2003/06/08 06:03:16 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.commons.validator; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.apache.commons.collections.FastHashMap; import org.apache.commons.validator.util.ValidatorUtils; /** * <p> * This contains the list of pluggable validators to run on a field and any message * information and variables to perform the validations and generate error * messages. Instances of this class are configured with a &lt;field&gt; xml element. * </p> * * @author David Winterfeldt * @author David Graham * @version $Revision: 1.18 $ $Date: 2003/06/08 06:03:16 $ * @see org.apache.commons.validator.Form */ public class Field implements Cloneable, Serializable { /** * This is the value that will be used as a key if the <code>Arg</code> * name field has no value. */ private static final String DEFAULT_ARG = "org.apache.commons.validator.Field.DEFAULT"; /** * This is the value that will be used as a key if the <code>Arg</code> * name field has no value. * @deprecated */ public static final String ARG_DEFAULT = DEFAULT_ARG; /** * This indicates an indexed property is being referenced. */ public static final String TOKEN_INDEXED = "[]"; protected static final String TOKEN_START = "${"; protected static final String TOKEN_END = "}"; protected static final String TOKEN_VAR = "var:"; protected String property = null; protected String indexedProperty = null; protected String indexedListProperty = null; protected String key = null; /** * A comma separated list of validator's this field depends on. */ protected String depends = null; protected int page = 0; protected int fieldOrder = 0; /** * @deprecated This is no longer used. */ protected FastHashMap hDependencies = new FastHashMap(); /** * Internal representation of this.depends String as a List. This List gets updated * whenever setDepends() gets called. This List is synchronized so a call to * setDepends() (which clears the List) won't interfere with a call to * isDependency(). */ private List dependencyList = Collections.synchronizedList(new ArrayList()); protected FastHashMap hVars = new FastHashMap(); protected FastHashMap hMsgs = new FastHashMap(); /** * Holds Maps of arguments. args[0] returns the Map for the first replacement * argument. */ protected Map[] args = new Map[10]; /** * @deprecated This variable is no longer used, use args instead. */ protected FastHashMap hArg0 = new FastHashMap(); /** * @deprecated This variable is no longer used, use args instead. */ protected FastHashMap hArg1 = new FastHashMap(); /** * @deprecated This variable is no longer used, use args instead. */ protected FastHashMap hArg2 = new FastHashMap(); /** * @deprecated This variable is no longer used, use args instead. */ protected FastHashMap hArg3 = new FastHashMap(); /** * Gets the page value that the Field is associated with for * validation. */ public int getPage() { return this.page; } /** * Sets the page value that the Field is associated with for * validation. */ public void setPage(int page) { this.page = page; } /** * Gets the position of the <code>Field</code> in the validation list. */ public int getFieldOrder() { return this.fieldOrder; } /** * Sets the position of the <code>Field</code> in the validation list. */ public void setFieldOrder(int fieldOrder) { this.fieldOrder = fieldOrder; } /** * Gets the property name of the field. */ public String getProperty() { return this.property; } /** * Sets the property name of the field. */ public void setProperty(String property) { this.property = property; } /** * Gets the indexed property name of the field. This * is the method name that can take an <code>int</code> as * a parameter for indexed property value retrieval. */ public String getIndexedProperty() { return this.indexedProperty; } /** * Sets the indexed property name of the field. */ public void setIndexedProperty(String indexedProperty) { this.indexedProperty = indexedProperty; } /** * Gets the indexed property name of the field. This * is the method name that will return an array or a * <code>Collection</code> used to retrieve the * list and then loop through the list performing the specified * validations. */ public String getIndexedListProperty() { return this.indexedListProperty; } /** * Sets the indexed property name of the field. */ public void setIndexedListProperty(String indexedListProperty) { this.indexedListProperty = indexedListProperty; } /** * Gets the validation rules for this field as a comma separated list. */ public String getDepends() { return this.depends; } /** * Sets the validation rules for this field as a comma separated list. */ public void setDepends(String depends) { this.depends = depends; this.dependencyList.clear(); StringTokenizer st = new StringTokenizer(depends, ","); while (st.hasMoreTokens()) { String depend = st.nextToken().trim(); if (depend != null && depend.length() > 0) { this.dependencyList.add(depend); } } } /** * Add a <code>Msg</code> to the <code>Field</code>. */ public void addMsg(Msg msg) { if (msg != null && msg.getKey() != null && msg.getKey().length() > 0 && msg.getName() != null && msg.getName().length() > 0) { hMsgs.put(msg.getName(), msg.getKey()); } } /** * Retrieve a message value. */ public String getMsg(String key) { return (String)hMsgs.get(key); } /** * Add an <code>Arg</code> to the replacement argument list. */ public void addArg(Arg arg) { // TODO this first if check can go away after arg0, etc. are removed from dtd if (arg == null || arg.getKey() == null || arg.getKey().length() == 0) { return; } this.ensureArgsCapacity(arg); Map argMap = (Map) this.args[arg.getPosition()]; if (argMap == null) { argMap = new HashMap(); this.args[arg.getPosition()] = argMap; } if (arg.getName() == null) { argMap.put(DEFAULT_ARG, arg); } else { argMap.put(arg.getName(), arg); } } /** * Ensures that the args array can hold the given arg. Resizes the array as * necessary. * @param arg Determine if the args array is long enough to store this arg's * position. */ private void ensureArgsCapacity(Arg arg) { if (arg.getPosition() >= this.args.length) { Map[] newArgs = new Map[arg.getPosition() + 1]; System.arraycopy(this.args, 0, newArgs, 0, this.args.length); this.args = newArgs; } } /** * Gets the default <code>Arg</code> object at the given position. * @return The default Arg or null if not found. */ public Arg getArg(int position) { return this.getArg(DEFAULT_ARG, position); } /** * Gets the default <code>Arg</code> object at the given position. If the key * finds a <code>null</code> value then the default value will try to be retrieved. * @param key The name the Arg is stored under. If not found, the default Arg for * the given position (if any) will be retrieved. * @param position The Arg number to find. * @return The Arg with the given name and position or null if not found. */ public Arg getArg(String key, int position) { if ((position >= this.args.length) || (this.args[position] == null)) { return null; } Arg arg = (Arg) args[position].get(key); // Didn't find default arg so exit, otherwise we would get into infinite recursion if ((arg == null) && key.equals(DEFAULT_ARG)) { return null; } return (arg == null) ? this.getArg(position) : arg; } /** * Add a <code>Arg</code> to the arg0 list. * @deprecated Use addArg(Arg) instead. */ public void addArg0(Arg arg) { arg.setPosition(0); this.addArg(arg); } /** * Gets the default arg0 <code>Arg</code> object. * @deprecated Use getArg(0) instead. */ public Arg getArg0() { return this.getArg(0); } /** * Gets the arg0 <code>Arg</code> object based on the key passed in. If the key * finds a <code>null</code> value then the default value will try to be retrieved. * @deprecated Use getArg(String, 0) instead. */ public Arg getArg0(String key) { return this.getArg(key, 0); } /** * Add a <code>Arg</code> to the arg1 list. * @deprecated Use addArg(Arg) instead. */ public void addArg1(Arg arg) { arg.setPosition(1); this.addArg(arg); } /** * Gets the default arg1 <code>Arg</code> object. * @deprecated Use getArg(1) instead. */ public Arg getArg1() { return this.getArg(1); } /** * Gets the arg1 <code>Arg</code> object based on the key passed in. If the key * finds a <code>null</code> value then the default value will try to be retrieved. * @deprecated Use getArg(String, 1) instead. */ public Arg getArg1(String key) { return this.getArg(key, 1); } /** * Add a <code>Arg</code> to the arg2 list. * @deprecated Use addArg(Arg) instead. */ public void addArg2(Arg arg) { arg.setPosition(2); this.addArg(arg); } /** * Gets the default arg2 <code>Arg</code> object. * @deprecated Use getArg(2) instead. */ public Arg getArg2() { return this.getArg(2); } /** * Gets the arg2 <code>Arg</code> object based on the key passed in. If the key * finds a <code>null</code> value then the default value will try to be retrieved. * @deprecated Use getArg(String, 2) instead. */ public Arg getArg2(String key) { return this.getArg(key, 2); } /** * Add a <code>Arg</code> to the arg3 list. * @deprecated Use addArg(Arg) instead. */ public void addArg3(Arg arg) { arg.setPosition(3); this.addArg(arg); } /** * Gets the default arg3 <code>Arg</code> object. * @deprecated Use getArg(3) instead. */ public Arg getArg3() { return this.getArg(3); } /** * Gets the arg3 <code>Arg</code> object based on the key passed in. If the key * finds a <code>null</code> value then the default value will try to be retrieved. * @deprecated Use getArg(String, 3) instead. */ public Arg getArg3(String key) { return this.getArg(key, 3); } /** * Add a <code>Var</code> to the <code>Field</code>. */ public void addVar(Var v) { this.hVars.put(v.getName(), v); } /** * Add a <code>Var</code>, based on the values passed in, to the * <code>Field</code>. * @deprecated Use addVar(String, String, String) instead. */ public void addVarParam(String name, String value, String jsType) { this.addVar(new Var(name, value, jsType)); } /** * Add a <code>Var</code>, based on the values passed in, to the * <code>Field</code>. */ public void addVar(String name, String value, String jsType) { this.addVar(new Var(name, value, jsType)); } /** * Retrieve a variable. */ public Var getVar(String mainKey) { return (Var) hVars.get(mainKey); } /** * Retrieve a variable's value. */ public String getVarValue(String mainKey) { String value = null; Object o = hVars.get(mainKey); if (o != null && o instanceof Var) { Var v = (Var) o; value = v.getValue(); } return value; } /** * The <code>Field</code>'s variables are returned as an * unmodifiable <code>Map</code>. */ public Map getVars() { return Collections.unmodifiableMap(hVars); } /** * Gets a unique key based on the property and indexedProperty fields. */ public String getKey() { if (this.key == null) { this.generateKey(); } return this.key; } /** * Sets a unique key for the field. This can be used to change * the key temporarily to have a unique key for an indexed field. */ public void setKey(String key) { this.key = key; } /** * If there is a value specified for the indexedProperty field then * <code>true</code> will be returned. Otherwise it will be <code>false</code>. */ public boolean isIndexed() { return ((indexedListProperty != null && indexedListProperty.length() > 0)); } /** * Generate correct <code>key</code> value. */ public void generateKey() { if (this.isIndexed()) { this.key = this.indexedListProperty + TOKEN_INDEXED + "." + this.property; } else { this.key = this.property; } } /** * Replace constants with values in fields and process the depends field * to create the dependency <code>Map</code>. * @deprecated This method is called by the framework. It will be made protected * in a future release. TODO */ public void process(Map globalConstants, Map constants) { this.hMsgs.setFast(false); this.hVars.setFast(true); this.generateKey(); // Process FormSet Constants for (Iterator i = constants.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); String key2 = TOKEN_START + key + TOKEN_END; String replaceValue = (String) constants.get(key); property = ValidatorUtils.replace(property, key2, replaceValue); processVars(key2, replaceValue); this.processMessageComponents(key2, replaceValue); } // Process Global Constants for (Iterator i = globalConstants.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); String key2 = TOKEN_START + key + TOKEN_END; String replaceValue = (String) globalConstants.get(key); property = ValidatorUtils.replace(property, key2, replaceValue); processVars(key2, replaceValue); this.processMessageComponents(key2, replaceValue); } // Process Var Constant Replacement for (Iterator i = hVars.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); String key2 = TOKEN_START + TOKEN_VAR + key + TOKEN_END; Var var = this.getVar(key); String replaceValue = var.getValue(); this.processMessageComponents(key2, replaceValue); } hMsgs.setFast(true); } /** * Replace the vars value with the key/value pairs passed in. */ private void processVars(String key, String replaceValue) { Iterator i = this.hVars.keySet().iterator(); while (i.hasNext()) { String varKey = (String) i.next(); Var var = this.getVar(varKey); var.setValue(ValidatorUtils.replace(var.getValue(), key, replaceValue)); } } /** * Replace the args key value with the key/value pairs passed in. * @deprecated This is an internal setup method that clients don't need to call. */ public void processMessageComponents(String key, String replaceValue) { this.internalProcessMessageComponents(key, replaceValue); } /** * Replace the args key value with the key/value pairs passed in. * TODO When processMessageComponents() is removed from the public API we * should rename this private method to "processMessageComponents". */ private void internalProcessMessageComponents(String key, String replaceValue) { String varKey = TOKEN_START + TOKEN_VAR; // Process Messages if (key != null && !key.startsWith(varKey)) { for (Iterator i = hMsgs.keySet().iterator(); i.hasNext();) { String msgKey = (String) i.next(); String value = this.getMsg(msgKey); hMsgs.put(msgKey, ValidatorUtils.replace(value, key, replaceValue)); } } this.processArg(key, replaceValue); } /** * Replace the arg <code>Collection</code> key value with the key/value pairs * passed in. */ private void processArg(String key, String replaceValue) { for (int i = 0; i < this.args.length; i++) { Map argMap = this.args[i]; if (argMap == null) { continue; } Iterator iter = argMap.values().iterator(); while (iter.hasNext()) { Arg arg = (Arg) iter.next(); if (arg != null) { arg.setKey( ValidatorUtils.replace(arg.getKey(), key, replaceValue)); } } } } /** * Checks if the validator is listed as a dependency. */ public boolean isDependency(String validatorName) { return this.dependencyList.contains(validatorName); } /** * Gets an unmodifiable <code>Set</code> of the dependencies. * @deprecated Use getDependencyList() instead. */ public Collection getDependencies() { return this.getDependencyList(); } /** * Gets an unmodifiable <code>List</code> of the dependencies in the same order * they were defined in parameter passed to the setDepends() method. */ public List getDependencyList() { return Collections.unmodifiableList(this.dependencyList); } /** * Creates and returns a copy of this object. */ public Object clone() { try { Field field = (Field) super.clone(); field.args = new Map[this.args.length]; for (int i = 0; i < this.args.length; i++) { Map argMap = new HashMap(this.args[i]); Iterator iter = argMap.keySet().iterator(); while (iter.hasNext()) { String validatorName = (String) iter.next(); Arg arg = (Arg) argMap.get(validatorName); argMap.put(validatorName, arg.clone()); } field.args[i] = argMap; } field.hVars = ValidatorUtils.copyFastHashMap(hVars); field.hMsgs = ValidatorUtils.copyFastHashMap(hMsgs); field.hArg0 = ValidatorUtils.copyFastHashMap(hArg0); field.hArg1 = ValidatorUtils.copyFastHashMap(hArg1); field.hArg2 = ValidatorUtils.copyFastHashMap(hArg2); field.hArg3 = ValidatorUtils.copyFastHashMap(hArg3); return field; } catch (CloneNotSupportedException e) { throw new InternalError(e.toString()); } } /** * Returns a string representation of the object. */ public String toString() { StringBuffer results = new StringBuffer(); results.append("\t\tkey = " + key + "\n"); results.append("\t\tproperty = " + property + "\n"); results.append("\t\tindexedProperty = " + indexedProperty + "\n"); results.append("\t\tindexedListProperty = " + indexedListProperty + "\n"); results.append("\t\tdepends = " + depends + "\n"); results.append("\t\tpage = " + page + "\n"); results.append("\t\tfieldOrder = " + fieldOrder + "\n"); if (hVars != null) { results.append("\t\tVars:\n"); for (Iterator i = hVars.keySet().iterator(); i.hasNext();) { Object key = i.next(); results.append("\t\t\t"); results.append(key); results.append("="); results.append(hVars.get(key)); results.append("\n"); } } return results.toString(); } }
Fixed NPE in clone(). git-svn-id: c96248f4ce6931c9674b921fd55ab67490fa1adf@140028 13f79535-47bb-0310-9956-ffa450edef68
src/share/org/apache/commons/validator/Field.java
Fixed NPE in clone().
<ide><path>rc/share/org/apache/commons/validator/Field.java <ide> /* <del> * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//validator/src/share/org/apache/commons/validator/Field.java,v 1.18 2003/06/08 06:03:16 dgraham Exp $ <del> * $Revision: 1.18 $ <del> * $Date: 2003/06/08 06:03:16 $ <add> * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//validator/src/share/org/apache/commons/validator/Field.java,v 1.19 2003/06/12 01:04:11 dgraham Exp $ <add> * $Revision: 1.19 $ <add> * $Date: 2003/06/12 01:04:11 $ <ide> * <ide> * ==================================================================== <ide> * <ide> * <ide> * @author David Winterfeldt <ide> * @author David Graham <del> * @version $Revision: 1.18 $ $Date: 2003/06/08 06:03:16 $ <add> * @version $Revision: 1.19 $ $Date: 2003/06/12 01:04:11 $ <ide> * @see org.apache.commons.validator.Form <ide> */ <ide> public class Field implements Cloneable, Serializable { <ide> * Creates and returns a copy of this object. <ide> */ <ide> public Object clone() { <add> Field field = null; <ide> try { <del> Field field = (Field) super.clone(); <del> <del> field.args = new Map[this.args.length]; <del> for (int i = 0; i < this.args.length; i++) { <del> Map argMap = new HashMap(this.args[i]); <del> Iterator iter = argMap.keySet().iterator(); <del> while (iter.hasNext()) { <del> String validatorName = (String) iter.next(); <del> Arg arg = (Arg) argMap.get(validatorName); <del> argMap.put(validatorName, arg.clone()); <del> } <del> field.args[i] = argMap; <del> } <del> <del> field.hVars = ValidatorUtils.copyFastHashMap(hVars); <del> field.hMsgs = ValidatorUtils.copyFastHashMap(hMsgs); <del> field.hArg0 = ValidatorUtils.copyFastHashMap(hArg0); <del> field.hArg1 = ValidatorUtils.copyFastHashMap(hArg1); <del> field.hArg2 = ValidatorUtils.copyFastHashMap(hArg2); <del> field.hArg3 = ValidatorUtils.copyFastHashMap(hArg3); <del> <del> return field; <add> field = (Field) super.clone(); <ide> } catch (CloneNotSupportedException e) { <ide> throw new InternalError(e.toString()); <ide> } <add> <add> field.args = new Map[this.args.length]; <add> for (int i = 0; i < this.args.length; i++) { <add> if (this.args[i] == null) { <add> continue; <add> } <add> <add> Map argMap = new HashMap(this.args[i]); <add> Iterator iter = argMap.keySet().iterator(); <add> while (iter.hasNext()) { <add> String validatorName = (String) iter.next(); <add> Arg arg = (Arg) argMap.get(validatorName); <add> argMap.put(validatorName, arg.clone()); <add> } <add> field.args[i] = argMap; <add> } <add> <add> field.hVars = ValidatorUtils.copyFastHashMap(hVars); <add> field.hMsgs = ValidatorUtils.copyFastHashMap(hMsgs); <add> field.hArg0 = ValidatorUtils.copyFastHashMap(hArg0); <add> field.hArg1 = ValidatorUtils.copyFastHashMap(hArg1); <add> field.hArg2 = ValidatorUtils.copyFastHashMap(hArg2); <add> field.hArg3 = ValidatorUtils.copyFastHashMap(hArg3); <add> <add> return field; <ide> } <ide> <ide> /**
Java
apache-2.0
014d3a1acf2fd8b8e0ab9a7fed62663ccaea000f
0
i-net-software/JWebAssembly,i-net-software/JWebAssembly
/* * Copyright 2017 Volker Berlin (i-net software) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.inetsoftware.jwebassembly.binary; /** * Instruction opcodes of the binary WebAssembly format. * * @author Volker Berlin * */ interface InstructionOpcodes { // === Control flow operators ==== static final int BLOCK = 0x02; static final int LOOP = 0x03; static final int IF = 0x04; static final int ELSE = 0x05; static final int END = 0x0B; static final int RETURN = 0x0F; static final int CALL = 0x10; // === Variable access =========== static final int GET_LOCAL = 0x20; static final int SET_LOCAL = 0x21; static final int I32_CONST = 0x41; static final int I64_CONST = 0x42; static final int F32_CONST = 0x43; static final int F64_CONST = 0x44; // === numerical operations ====== static final int I32_EQZ = 0x45; static final int I32_EQ = 0x46; static final int I32_NE = 0x47; static final int I32_LT_S = 0x48; static final int I32_LT_U = 0x49; static final int I32_GT_S = 0x4A; static final int I32_GT_U = 0x4B; static final int I32_LE_S = 0x4C; static final int I32_LE_U = 0x4D; static final int I32_GE_S = 0x4E; static final int I32_GE_U = 0x4F; static final int I64_EQZ = 0x50; static final int I64_EQ = 0x51; static final int I64_NE = 0x52; static final int I64_LT_S = 0x53; static final int I64_LT_U = 0x54; static final int I64_GT_S = 0x55; static final int I64_GT_U = 0x56; static final int I64_LE_S = 0x57; static final int I64_LE_U = 0x58; static final int I64_GE_S = 0x59; static final int I64_GE_U = 0x5A; static final int F32_EQ = 0x5B; static final int F32_NE = 0x5C; static final int F32_LT = 0x5D; static final int F32_GT = 0x5E; static final int F32_LE = 0x5F; static final int F32_GE = 0x60; static final int F64_EQ = 0x61; static final int F64_NE = 0x62; static final int F64_LT = 0x63; static final int F64_GT = 0x64; static final int F64_LE = 0x65; static final int F64_GE = 0x66; static final int I32_CLZ = 0x67; static final int I32_CTZ = 0x68; static final int I32_POPCNT= 0x69; static final int I32_ADD = 0x6A; static final int I32_SUB = 0x6B; static final int I32_MUL = 0x6C; static final int I32_DIV_S = 0x6D; static final int I32_DIV_U = 0x6E; static final int I32_REM_S = 0x6F; static final int I32_REM_U = 0x70; static final int I32_AND = 0x71; static final int I32_OR = 0x72; static final int I32_XOR = 0x73; static final int I32_SHL = 0x74; static final int I32_SHR_S = 0x75; static final int I32_SHR_U = 0x76; static final int I32_ROTL = 0x77; static final int I32_ROTR = 0x78; static final int I64_CLZ = 0x79; static final int I64_CTZ = 0x7A; static final int I64_POPCNT= 0x7B; static final int I64_ADD = 0x7C; static final int I64_SUB = 0x7D; static final int I64_MUL = 0x7E; static final int I64_DIV_S = 0x7F; static final int I64_REM_S = 0x81; static final int I64_AND = 0x83; static final int I64_OR = 0x84; static final int I64_XOR = 0x85; static final int I64_SHL = 0x86; static final int I64_SHR_S = 0x87; static final int I64_SHR_U = 0x88; static final int F32_ADD = 0x92; static final int F32_SUB = 0x93; static final int F32_MUL = 0x94; static final int F32_DIV = 0x95; static final int F64_ADD = 0xA0; static final int F64_SUB = 0xA1; static final int F64_MUL = 0xA2; static final int F64_DIV = 0xA3; // === data type conversions ===== static final int I32_WRAP_I64 = 0xA7; static final int I64_EXTEND_S_I32 = 0xAC; }
src/de/inetsoftware/jwebassembly/binary/InstructionOpcodes.java
/* * Copyright 2017 Volker Berlin (i-net software) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.inetsoftware.jwebassembly.binary; /** * Instruction opcodes of the binary WebAssembly format. * * @author Volker Berlin * */ interface InstructionOpcodes { // === Control flow operators ==== static final int BLOCK = 0x02; static final int LOOP = 0x03; static final int IF = 0x04; static final int ELSE = 0x05; static final int END = 0x0B; static final int RETURN = 0x0F; static final int CALL = 0x10; // === Variable access =========== static final int GET_LOCAL = 0x20; static final int SET_LOCAL = 0x21; static final int I32_CONST = 0x41; static final int I64_CONST = 0x42; static final int F32_CONST = 0x43; static final int F64_CONST = 0x44; // === numerical operations ====== static final int I32_ADD = 0x6A; static final int I32_SUB = 0x6B; static final int I32_MUL = 0x6C; static final int I32_DIV_S = 0x6D; static final int I32_REM_S = 0x6F; static final int I32_AND = 0x71; static final int I32_OR = 0x72; static final int I32_XOR = 0x73; static final int I32_SHL = 0x74; static final int I32_SHR_S = 0x75; static final int I32_SHR_U = 0x76; static final int I64_ADD = 0x7C; static final int I64_SUB = 0x7D; static final int I64_MUL = 0x7E; static final int I64_DIV_S = 0x7F; static final int I64_REM_S = 0x81; static final int I64_AND = 0x83; static final int I64_OR = 0x84; static final int I64_XOR = 0x85; static final int I64_SHL = 0x86; static final int I64_SHR_S = 0x87; static final int I64_SHR_U = 0x88; static final int F32_ADD = 0x92; static final int F32_SUB = 0x93; static final int F32_MUL = 0x94; static final int F32_DIV = 0x95; static final int F64_ADD = 0xA0; static final int F64_SUB = 0xA1; static final int F64_MUL = 0xA2; static final int F64_DIV = 0xA3; // === data type conversions ===== static final int I32_WRAP_I64 = 0xA7; static final int I64_EXTEND_S_I32 = 0xAC; }
Add more numerical operations
src/de/inetsoftware/jwebassembly/binary/InstructionOpcodes.java
Add more numerical operations
<ide><path>rc/de/inetsoftware/jwebassembly/binary/InstructionOpcodes.java <ide> <ide> // === numerical operations ====== <ide> <add> static final int I32_EQZ = 0x45; <add> <add> static final int I32_EQ = 0x46; <add> <add> static final int I32_NE = 0x47; <add> <add> static final int I32_LT_S = 0x48; <add> <add> static final int I32_LT_U = 0x49; <add> <add> static final int I32_GT_S = 0x4A; <add> <add> static final int I32_GT_U = 0x4B; <add> <add> static final int I32_LE_S = 0x4C; <add> <add> static final int I32_LE_U = 0x4D; <add> <add> static final int I32_GE_S = 0x4E; <add> <add> static final int I32_GE_U = 0x4F; <add> <add> static final int I64_EQZ = 0x50; <add> <add> static final int I64_EQ = 0x51; <add> <add> static final int I64_NE = 0x52; <add> <add> static final int I64_LT_S = 0x53; <add> <add> static final int I64_LT_U = 0x54; <add> <add> static final int I64_GT_S = 0x55; <add> <add> static final int I64_GT_U = 0x56; <add> <add> static final int I64_LE_S = 0x57; <add> <add> static final int I64_LE_U = 0x58; <add> <add> static final int I64_GE_S = 0x59; <add> <add> static final int I64_GE_U = 0x5A; <add> <add> static final int F32_EQ = 0x5B; <add> <add> static final int F32_NE = 0x5C; <add> <add> static final int F32_LT = 0x5D; <add> <add> static final int F32_GT = 0x5E; <add> <add> static final int F32_LE = 0x5F; <add> <add> static final int F32_GE = 0x60; <add> <add> static final int F64_EQ = 0x61; <add> <add> static final int F64_NE = 0x62; <add> <add> static final int F64_LT = 0x63; <add> <add> static final int F64_GT = 0x64; <add> <add> static final int F64_LE = 0x65; <add> <add> static final int F64_GE = 0x66; <add> <add> static final int I32_CLZ = 0x67; <add> <add> static final int I32_CTZ = 0x68; <add> <add> static final int I32_POPCNT= 0x69; <add> <ide> static final int I32_ADD = 0x6A; <ide> <ide> static final int I32_SUB = 0x6B; <ide> <ide> static final int I32_DIV_S = 0x6D; <ide> <add> static final int I32_DIV_U = 0x6E; <add> <ide> static final int I32_REM_S = 0x6F; <ide> <add> static final int I32_REM_U = 0x70; <add> <ide> static final int I32_AND = 0x71; <ide> <ide> static final int I32_OR = 0x72; <ide> static final int I32_SHR_S = 0x75; <ide> <ide> static final int I32_SHR_U = 0x76; <add> <add> static final int I32_ROTL = 0x77; <add> <add> static final int I32_ROTR = 0x78; <add> <add> static final int I64_CLZ = 0x79; <add> <add> static final int I64_CTZ = 0x7A; <add> <add> static final int I64_POPCNT= 0x7B; <ide> <ide> static final int I64_ADD = 0x7C; <ide>
Java
apache-2.0
e25ccb91ae6cb81739131acb7074bbfc60d4c13d
0
sreeramjayan/elasticsearch,Shepard1212/elasticsearch,strapdata/elassandra5-rc,qwerty4030/elasticsearch,jprante/elasticsearch,rajanm/elasticsearch,nezirus/elasticsearch,awislowski/elasticsearch,palecur/elasticsearch,C-Bish/elasticsearch,scottsom/elasticsearch,awislowski/elasticsearch,markwalkom/elasticsearch,brandonkearby/elasticsearch,nknize/elasticsearch,maddin2016/elasticsearch,mohit/elasticsearch,strapdata/elassandra5-rc,umeshdangat/elasticsearch,dongjoon-hyun/elasticsearch,sneivandt/elasticsearch,uschindler/elasticsearch,myelin/elasticsearch,robin13/elasticsearch,robin13/elasticsearch,obourgain/elasticsearch,wangtuo/elasticsearch,jimczi/elasticsearch,lks21c/elasticsearch,fred84/elasticsearch,mikemccand/elasticsearch,ZTE-PaaS/elasticsearch,a2lin/elasticsearch,liweinan0423/elasticsearch,kalimatas/elasticsearch,Shepard1212/elasticsearch,camilojd/elasticsearch,gfyoung/elasticsearch,pozhidaevak/elasticsearch,elasticdog/elasticsearch,nilabhsagar/elasticsearch,liweinan0423/elasticsearch,JervyShi/elasticsearch,strapdata/elassandra,xuzha/elasticsearch,s1monw/elasticsearch,C-Bish/elasticsearch,nomoa/elasticsearch,kalimatas/elasticsearch,scottsom/elasticsearch,bawse/elasticsearch,mortonsykes/elasticsearch,jimczi/elasticsearch,girirajsharma/elasticsearch,wuranbo/elasticsearch,dongjoon-hyun/elasticsearch,myelin/elasticsearch,dpursehouse/elasticsearch,vroyer/elasticassandra,uschindler/elasticsearch,ZTE-PaaS/elasticsearch,spiegela/elasticsearch,yanjunh/elasticsearch,awislowski/elasticsearch,sreeramjayan/elasticsearch,avikurapati/elasticsearch,sreeramjayan/elasticsearch,sneivandt/elasticsearch,naveenhooda2000/elasticsearch,palecur/elasticsearch,MisterAndersen/elasticsearch,fernandozhu/elasticsearch,sneivandt/elasticsearch,mortonsykes/elasticsearch,StefanGor/elasticsearch,gingerwizard/elasticsearch,C-Bish/elasticsearch,wangtuo/elasticsearch,clintongormley/elasticsearch,scorpionvicky/elasticsearch,uschindler/elasticsearch,strapdata/elassandra,nilabhsagar/elasticsearch,JackyMai/elasticsearch,liweinan0423/elasticsearch,IanvsPoplicola/elasticsearch,gingerwizard/elasticsearch,masaruh/elasticsearch,ThiagoGarciaAlves/elasticsearch,mikemccand/elasticsearch,wangtuo/elasticsearch,yynil/elasticsearch,GlenRSmith/elasticsearch,strapdata/elassandra5-rc,mohit/elasticsearch,elasticdog/elasticsearch,henakamaMSFT/elasticsearch,cwurm/elasticsearch,HonzaKral/elasticsearch,mmaracic/elasticsearch,a2lin/elasticsearch,jimczi/elasticsearch,mjason3/elasticsearch,gingerwizard/elasticsearch,nazarewk/elasticsearch,nezirus/elasticsearch,clintongormley/elasticsearch,HonzaKral/elasticsearch,jprante/elasticsearch,vroyer/elassandra,xuzha/elasticsearch,LeoYao/elasticsearch,shreejay/elasticsearch,myelin/elasticsearch,alexshadow007/elasticsearch,LewayneNaidoo/elasticsearch,JSCooke/elasticsearch,wuranbo/elasticsearch,lks21c/elasticsearch,girirajsharma/elasticsearch,myelin/elasticsearch,s1monw/elasticsearch,JervyShi/elasticsearch,mikemccand/elasticsearch,geidies/elasticsearch,clintongormley/elasticsearch,markwalkom/elasticsearch,pozhidaevak/elasticsearch,strapdata/elassandra,zkidkid/elasticsearch,yanjunh/elasticsearch,trangvh/elasticsearch,vroyer/elasticassandra,naveenhooda2000/elasticsearch,trangvh/elasticsearch,fforbeck/elasticsearch,dongjoon-hyun/elasticsearch,xuzha/elasticsearch,winstonewert/elasticsearch,C-Bish/elasticsearch,gingerwizard/elasticsearch,sreeramjayan/elasticsearch,LeoYao/elasticsearch,cwurm/elasticsearch,uschindler/elasticsearch,ricardocerq/elasticsearch,nilabhsagar/elasticsearch,scottsom/elasticsearch,nazarewk/elasticsearch,nknize/elasticsearch,MisterAndersen/elasticsearch,MaineC/elasticsearch,fred84/elasticsearch,mmaracic/elasticsearch,coding0011/elasticsearch,strapdata/elassandra5-rc,JackyMai/elasticsearch,pozhidaevak/elasticsearch,liweinan0423/elasticsearch,mjason3/elasticsearch,JervyShi/elasticsearch,girirajsharma/elasticsearch,jimczi/elasticsearch,glefloch/elasticsearch,gingerwizard/elasticsearch,a2lin/elasticsearch,umeshdangat/elasticsearch,henakamaMSFT/elasticsearch,maddin2016/elasticsearch,LeoYao/elasticsearch,masaruh/elasticsearch,obourgain/elasticsearch,IanvsPoplicola/elasticsearch,jprante/elasticsearch,kalimatas/elasticsearch,coding0011/elasticsearch,umeshdangat/elasticsearch,Stacey-Gammon/elasticsearch,wenpos/elasticsearch,gmarz/elasticsearch,rajanm/elasticsearch,palecur/elasticsearch,Shepard1212/elasticsearch,LewayneNaidoo/elasticsearch,spiegela/elasticsearch,artnowo/elasticsearch,strapdata/elassandra,winstonewert/elasticsearch,mmaracic/elasticsearch,rajanm/elasticsearch,JervyShi/elasticsearch,elasticdog/elasticsearch,ThiagoGarciaAlves/elasticsearch,sneivandt/elasticsearch,glefloch/elasticsearch,scorpionvicky/elasticsearch,mjason3/elasticsearch,nknize/elasticsearch,gfyoung/elasticsearch,HonzaKral/elasticsearch,JSCooke/elasticsearch,lks21c/elasticsearch,alexshadow007/elasticsearch,coding0011/elasticsearch,mortonsykes/elasticsearch,gmarz/elasticsearch,fernandozhu/elasticsearch,cwurm/elasticsearch,rlugojr/elasticsearch,Helen-Zhao/elasticsearch,obourgain/elasticsearch,JSCooke/elasticsearch,fred84/elasticsearch,markwalkom/elasticsearch,sneivandt/elasticsearch,nezirus/elasticsearch,cwurm/elasticsearch,gfyoung/elasticsearch,awislowski/elasticsearch,markwalkom/elasticsearch,Shepard1212/elasticsearch,wuranbo/elasticsearch,Stacey-Gammon/elasticsearch,camilojd/elasticsearch,mmaracic/elasticsearch,henakamaMSFT/elasticsearch,geidies/elasticsearch,pozhidaevak/elasticsearch,artnowo/elasticsearch,masaruh/elasticsearch,alexshadow007/elasticsearch,Helen-Zhao/elasticsearch,i-am-Nathan/elasticsearch,mohit/elasticsearch,awislowski/elasticsearch,xuzha/elasticsearch,elasticdog/elasticsearch,obourgain/elasticsearch,avikurapati/elasticsearch,fernandozhu/elasticsearch,pozhidaevak/elasticsearch,kalimatas/elasticsearch,StefanGor/elasticsearch,rlugojr/elasticsearch,trangvh/elasticsearch,maddin2016/elasticsearch,clintongormley/elasticsearch,mjason3/elasticsearch,njlawton/elasticsearch,gmarz/elasticsearch,ZTE-PaaS/elasticsearch,strapdata/elassandra5-rc,fernandozhu/elasticsearch,njlawton/elasticsearch,wangtuo/elasticsearch,JervyShi/elasticsearch,yanjunh/elasticsearch,MaineC/elasticsearch,bawse/elasticsearch,zkidkid/elasticsearch,IanvsPoplicola/elasticsearch,masaruh/elasticsearch,ricardocerq/elasticsearch,winstonewert/elasticsearch,maddin2016/elasticsearch,palecur/elasticsearch,ThiagoGarciaAlves/elasticsearch,brandonkearby/elasticsearch,gingerwizard/elasticsearch,s1monw/elasticsearch,girirajsharma/elasticsearch,shreejay/elasticsearch,glefloch/elasticsearch,Stacey-Gammon/elasticsearch,njlawton/elasticsearch,mortonsykes/elasticsearch,robin13/elasticsearch,ricardocerq/elasticsearch,shreejay/elasticsearch,s1monw/elasticsearch,nknize/elasticsearch,brandonkearby/elasticsearch,palecur/elasticsearch,nazarewk/elasticsearch,i-am-Nathan/elasticsearch,spiegela/elasticsearch,GlenRSmith/elasticsearch,scorpionvicky/elasticsearch,zkidkid/elasticsearch,rajanm/elasticsearch,mohit/elasticsearch,LeoYao/elasticsearch,glefloch/elasticsearch,nazarewk/elasticsearch,nomoa/elasticsearch,yynil/elasticsearch,scorpionvicky/elasticsearch,dpursehouse/elasticsearch,fforbeck/elasticsearch,lks21c/elasticsearch,xuzha/elasticsearch,fred84/elasticsearch,s1monw/elasticsearch,mortonsykes/elasticsearch,kalimatas/elasticsearch,Shepard1212/elasticsearch,sreeramjayan/elasticsearch,xuzha/elasticsearch,gingerwizard/elasticsearch,dongjoon-hyun/elasticsearch,jprante/elasticsearch,vroyer/elassandra,fforbeck/elasticsearch,avikurapati/elasticsearch,IanvsPoplicola/elasticsearch,dpursehouse/elasticsearch,alexshadow007/elasticsearch,shreejay/elasticsearch,lks21c/elasticsearch,Stacey-Gammon/elasticsearch,yanjunh/elasticsearch,obourgain/elasticsearch,scottsom/elasticsearch,masaruh/elasticsearch,gmarz/elasticsearch,shreejay/elasticsearch,nezirus/elasticsearch,MaineC/elasticsearch,Stacey-Gammon/elasticsearch,qwerty4030/elasticsearch,avikurapati/elasticsearch,spiegela/elasticsearch,rlugojr/elasticsearch,nilabhsagar/elasticsearch,JackyMai/elasticsearch,mikemccand/elasticsearch,cwurm/elasticsearch,wenpos/elasticsearch,camilojd/elasticsearch,nknize/elasticsearch,umeshdangat/elasticsearch,trangvh/elasticsearch,StefanGor/elasticsearch,rajanm/elasticsearch,dpursehouse/elasticsearch,girirajsharma/elasticsearch,i-am-Nathan/elasticsearch,yynil/elasticsearch,MisterAndersen/elasticsearch,JervyShi/elasticsearch,clintongormley/elasticsearch,nomoa/elasticsearch,naveenhooda2000/elasticsearch,artnowo/elasticsearch,zkidkid/elasticsearch,nazarewk/elasticsearch,a2lin/elasticsearch,liweinan0423/elasticsearch,scorpionvicky/elasticsearch,LewayneNaidoo/elasticsearch,rlugojr/elasticsearch,alexshadow007/elasticsearch,umeshdangat/elasticsearch,HonzaKral/elasticsearch,LeoYao/elasticsearch,camilojd/elasticsearch,maddin2016/elasticsearch,GlenRSmith/elasticsearch,myelin/elasticsearch,JSCooke/elasticsearch,JackyMai/elasticsearch,uschindler/elasticsearch,LewayneNaidoo/elasticsearch,henakamaMSFT/elasticsearch,mmaracic/elasticsearch,bawse/elasticsearch,a2lin/elasticsearch,mikemccand/elasticsearch,girirajsharma/elasticsearch,MisterAndersen/elasticsearch,camilojd/elasticsearch,trangvh/elasticsearch,ricardocerq/elasticsearch,geidies/elasticsearch,yynil/elasticsearch,StefanGor/elasticsearch,LeoYao/elasticsearch,dpursehouse/elasticsearch,StefanGor/elasticsearch,sreeramjayan/elasticsearch,winstonewert/elasticsearch,geidies/elasticsearch,winstonewert/elasticsearch,yynil/elasticsearch,rajanm/elasticsearch,bawse/elasticsearch,wangtuo/elasticsearch,JSCooke/elasticsearch,MaineC/elasticsearch,avikurapati/elasticsearch,coding0011/elasticsearch,njlawton/elasticsearch,fernandozhu/elasticsearch,artnowo/elasticsearch,ThiagoGarciaAlves/elasticsearch,mmaracic/elasticsearch,LewayneNaidoo/elasticsearch,clintongormley/elasticsearch,wenpos/elasticsearch,jimczi/elasticsearch,henakamaMSFT/elasticsearch,artnowo/elasticsearch,qwerty4030/elasticsearch,markwalkom/elasticsearch,brandonkearby/elasticsearch,MaineC/elasticsearch,rlugojr/elasticsearch,fforbeck/elasticsearch,mohit/elasticsearch,fforbeck/elasticsearch,nilabhsagar/elasticsearch,nezirus/elasticsearch,GlenRSmith/elasticsearch,fred84/elasticsearch,i-am-Nathan/elasticsearch,ZTE-PaaS/elasticsearch,strapdata/elassandra,geidies/elasticsearch,gmarz/elasticsearch,MisterAndersen/elasticsearch,qwerty4030/elasticsearch,njlawton/elasticsearch,C-Bish/elasticsearch,i-am-Nathan/elasticsearch,robin13/elasticsearch,camilojd/elasticsearch,nomoa/elasticsearch,yanjunh/elasticsearch,ricardocerq/elasticsearch,jprante/elasticsearch,IanvsPoplicola/elasticsearch,robin13/elasticsearch,gfyoung/elasticsearch,vroyer/elassandra,wuranbo/elasticsearch,Helen-Zhao/elasticsearch,naveenhooda2000/elasticsearch,Helen-Zhao/elasticsearch,wenpos/elasticsearch,wuranbo/elasticsearch,nomoa/elasticsearch,ZTE-PaaS/elasticsearch,naveenhooda2000/elasticsearch,ThiagoGarciaAlves/elasticsearch,zkidkid/elasticsearch,qwerty4030/elasticsearch,spiegela/elasticsearch,gfyoung/elasticsearch,bawse/elasticsearch,LeoYao/elasticsearch,scottsom/elasticsearch,yynil/elasticsearch,geidies/elasticsearch,glefloch/elasticsearch,coding0011/elasticsearch,mjason3/elasticsearch,elasticdog/elasticsearch,dongjoon-hyun/elasticsearch,GlenRSmith/elasticsearch,Helen-Zhao/elasticsearch,markwalkom/elasticsearch,vroyer/elasticassandra,JackyMai/elasticsearch,brandonkearby/elasticsearch,ThiagoGarciaAlves/elasticsearch,wenpos/elasticsearch
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.query.support; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.AbstractQueryTestCase; import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.indices.query.IndicesQueriesRegistry; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.SearchModule; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.source.FetchSourceContext; import org.elasticsearch.search.highlight.HighlightBuilderTests; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.ScriptSortBuilder; import org.elasticsearch.search.sort.SortBuilder; import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.test.ESTestCase; import org.junit.AfterClass; import org.junit.BeforeClass; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.sameInstance; public class InnerHitBuilderTests extends ESTestCase { private static final int NUMBER_OF_TESTBUILDERS = 20; private static NamedWriteableRegistry namedWriteableRegistry; private static IndicesQueriesRegistry indicesQueriesRegistry; @BeforeClass public static void init() { namedWriteableRegistry = new NamedWriteableRegistry(); indicesQueriesRegistry = new SearchModule(Settings.EMPTY, namedWriteableRegistry).buildQueryParserRegistry(); } @AfterClass public static void afterClass() throws Exception { namedWriteableRegistry = null; indicesQueriesRegistry = null; } public void testSerialization() throws Exception { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { InnerHitBuilder original = randomInnerHits(); InnerHitBuilder deserialized = serializedCopy(original); assertEquals(deserialized, original); assertEquals(deserialized.hashCode(), original.hashCode()); assertNotSame(deserialized, original); } } public void testFromAndToXContent() throws Exception { QueryParseContext context = new QueryParseContext(indicesQueriesRegistry); context.parseFieldMatcher(new ParseFieldMatcher(Settings.EMPTY)); for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { InnerHitBuilder innerHit = randomInnerHits(); XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { builder.prettyPrint(); } innerHit.toXContent(builder, ToXContent.EMPTY_PARAMS); XContentParser parser = XContentHelper.createParser(builder.bytes()); context.reset(parser); InnerHitBuilder secondInnerHits = InnerHitBuilder.fromXContent(parser, context); assertThat(innerHit, not(sameInstance(secondInnerHits))); assertThat(innerHit, equalTo(secondInnerHits)); assertThat(innerHit.hashCode(), equalTo(secondInnerHits.hashCode())); } } public void testEqualsAndHashcode() throws IOException { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { InnerHitBuilder firstInnerHit = randomInnerHits(); assertFalse("inner hit is equal to null", firstInnerHit.equals(null)); assertFalse("inner hit is equal to incompatible type", firstInnerHit.equals("")); assertTrue("inner it is not equal to self", firstInnerHit.equals(firstInnerHit)); assertThat("same inner hit's hashcode returns different values if called multiple times", firstInnerHit.hashCode(), equalTo(firstInnerHit.hashCode())); assertThat("different inner hits should not be equal", mutate(firstInnerHit), not(equalTo(firstInnerHit))); InnerHitBuilder secondBuilder = serializedCopy(firstInnerHit); assertTrue("inner hit is not equal to self", secondBuilder.equals(secondBuilder)); assertTrue("inner hit is not equal to its copy", firstInnerHit.equals(secondBuilder)); assertTrue("equals is not symmetric", secondBuilder.equals(firstInnerHit)); assertThat("inner hits copy's hashcode is different from original hashcode", secondBuilder.hashCode(), equalTo(firstInnerHit.hashCode())); InnerHitBuilder thirdBuilder = serializedCopy(secondBuilder); assertTrue("inner hit is not equal to self", thirdBuilder.equals(thirdBuilder)); assertTrue("inner hit is not equal to its copy", secondBuilder.equals(thirdBuilder)); assertThat("inner hit copy's hashcode is different from original hashcode", secondBuilder.hashCode(), equalTo(thirdBuilder.hashCode())); assertTrue("equals is not transitive", firstInnerHit.equals(thirdBuilder)); assertThat("inner hit copy's hashcode is different from original hashcode", firstInnerHit.hashCode(), equalTo(thirdBuilder.hashCode())); assertTrue("equals is not symmetric", thirdBuilder.equals(secondBuilder)); assertTrue("equals is not symmetric", thirdBuilder.equals(firstInnerHit)); } } public static InnerHitBuilder randomInnerHits() { return randomInnerHits(true); } public static InnerHitBuilder randomInnerHits(boolean recursive) { InnerHitBuilder innerHits = new InnerHitBuilder(); if (randomBoolean()) { innerHits.setNestedPath(randomAsciiOfLengthBetween(1, 16)); } else { innerHits.setParentChildType(randomAsciiOfLengthBetween(1, 16)); } innerHits.setName(randomAsciiOfLengthBetween(1, 16)); innerHits.setFrom(randomIntBetween(0, 128)); innerHits.setSize(randomIntBetween(0, 128)); innerHits.setExplain(randomBoolean()); innerHits.setVersion(randomBoolean()); innerHits.setTrackScores(randomBoolean()); innerHits.setFieldNames(randomListStuff(16, () -> randomAsciiOfLengthBetween(1, 16))); innerHits.setFieldDataFields(randomListStuff(16, () -> randomAsciiOfLengthBetween(1, 16))); innerHits.setScriptFields(randomListStuff(16, InnerHitBuilderTests::randomScript)); FetchSourceContext randomFetchSourceContext; if (randomBoolean()) { randomFetchSourceContext = new FetchSourceContext(randomBoolean()); } else { randomFetchSourceContext = new FetchSourceContext( generateRandomStringArray(12, 16, false), generateRandomStringArray(12, 16, false) ); } innerHits.setFetchSourceContext(randomFetchSourceContext); if (randomBoolean()) { innerHits.setSorts(randomListStuff(16, () -> SortBuilders.fieldSort(randomAsciiOfLengthBetween(5, 20)).order(randomFrom(SortOrder.values()))) ); } innerHits.setHighlightBuilder(HighlightBuilderTests.randomHighlighterBuilder()); if (randomBoolean()) { innerHits.setQuery(new MatchQueryBuilder(randomAsciiOfLengthBetween(1, 16), randomAsciiOfLengthBetween(1, 16))); } if (recursive && randomBoolean()) { InnerHitsBuilder innerHitsBuilder = new InnerHitsBuilder(); int size = randomIntBetween(1, 16); for (int i = 0; i < size; i++) { innerHitsBuilder.addInnerHit(randomAsciiOfLengthBetween(1, 16), randomInnerHits(false)); } innerHits.setInnerHitsBuilder(innerHitsBuilder); } return innerHits; } static InnerHitBuilder mutate(InnerHitBuilder innerHits) throws IOException { InnerHitBuilder copy = serializedCopy(innerHits); int surprise = randomIntBetween(0, 10); switch (surprise) { case 0: copy.setFrom(randomValueOtherThan(innerHits.getFrom(), () -> randomIntBetween(0, 128))); break; case 1: copy.setSize(randomValueOtherThan(innerHits.getSize(), () -> randomIntBetween(0, 128))); break; case 2: copy.setExplain(!copy.isExplain()); break; case 3: copy.setVersion(!copy.isVersion()); break; case 4: copy.setTrackScores(!copy.isTrackScores()); break; case 5: copy.setName(randomValueOtherThan(innerHits.getName(), () -> randomAsciiOfLengthBetween(1, 16))); break; case 6: copy.setFieldDataFields(randomValueOtherThan(copy.getFieldDataFields(), () -> { return randomListStuff(16, () -> randomAsciiOfLengthBetween(1, 16)); })); break; case 7: copy.setScriptFields(randomValueOtherThan(copy.getScriptFields(), () -> { return randomListStuff(16, InnerHitBuilderTests::randomScript);})); break; case 8: copy.setFetchSourceContext(randomValueOtherThan(copy.getFetchSourceContext(), () -> { FetchSourceContext randomFetchSourceContext; if (randomBoolean()) { randomFetchSourceContext = new FetchSourceContext(randomBoolean()); } else { randomFetchSourceContext = new FetchSourceContext( generateRandomStringArray(12, 16, false), generateRandomStringArray(12, 16, false) ); } return randomFetchSourceContext; })); break; case 9: final List<SortBuilder<?>> sortBuilders = randomValueOtherThan(copy.getSorts(), () -> { List<SortBuilder<?>> builders = randomListStuff(16, () -> SortBuilders.fieldSort(randomAsciiOfLengthBetween(5, 20)).order(randomFrom(SortOrder.values()))); return builders; }); copy.setSorts(sortBuilders); break; case 10: copy.setHighlightBuilder(randomValueOtherThan(copy.getHighlightBuilder(), HighlightBuilderTests::randomHighlighterBuilder)); break; default: throw new IllegalStateException("unexpected surprise [" + surprise + "]"); } return copy; } static SearchSourceBuilder.ScriptField randomScript() { ScriptService.ScriptType randomScriptType = randomFrom(ScriptService.ScriptType.values()); Map<String, Object> randomMap = null; if (randomBoolean()) { randomMap = new HashMap<>(); int numEntries = randomIntBetween(0, 32); for (int i = 0; i < numEntries; i++) { randomMap.put(String.valueOf(i), randomAsciiOfLength(16)); } } Script script = new Script(randomAsciiOfLength(128), randomScriptType, randomAsciiOfLengthBetween(1, 4),randomMap); return new SearchSourceBuilder.ScriptField(randomAsciiOfLengthBetween(1, 32), script, randomBoolean()); } static <T> List<T> randomListStuff(int maxSize, Supplier<T> valueSupplier) { int size = randomIntBetween(0, maxSize); List<T> list = new ArrayList<>(size); for (int i = 0; i < size; i++) { list.add(valueSupplier.get()); } return list; } private static InnerHitBuilder serializedCopy(InnerHitBuilder original) throws IOException { try (BytesStreamOutput output = new BytesStreamOutput()) { original.writeTo(output); try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) { return new InnerHitBuilder(in); } } } }
core/src/test/java/org/elasticsearch/index/query/support/InnerHitBuilderTests.java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.query.support; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.AbstractQueryTestCase; import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.indices.query.IndicesQueriesRegistry; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.SearchModule; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.source.FetchSourceContext; import org.elasticsearch.search.highlight.HighlightBuilderTests; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.ScriptSortBuilder; import org.elasticsearch.search.sort.SortBuilder; import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.test.ESTestCase; import org.junit.AfterClass; import org.junit.BeforeClass; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.sameInstance; public class InnerHitBuilderTests extends ESTestCase { private static final int NUMBER_OF_TESTBUILDERS = 20; private static NamedWriteableRegistry namedWriteableRegistry; private static IndicesQueriesRegistry indicesQueriesRegistry; @BeforeClass public static void init() { namedWriteableRegistry = new NamedWriteableRegistry(); indicesQueriesRegistry = new SearchModule(Settings.EMPTY, namedWriteableRegistry).buildQueryParserRegistry(); } @AfterClass public static void afterClass() throws Exception { namedWriteableRegistry = null; indicesQueriesRegistry = null; } public void testSerialization() throws Exception { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { InnerHitBuilder original = randomInnerHits(); InnerHitBuilder deserialized = serializedCopy(original); assertEquals(deserialized, original); assertEquals(deserialized.hashCode(), original.hashCode()); assertNotSame(deserialized, original); } } public void testFromAndToXContent() throws Exception { QueryParseContext context = new QueryParseContext(indicesQueriesRegistry); context.parseFieldMatcher(new ParseFieldMatcher(Settings.EMPTY)); for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { InnerHitBuilder innerHit = randomInnerHits(); XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { builder.prettyPrint(); } innerHit.toXContent(builder, ToXContent.EMPTY_PARAMS); XContentParser parser = XContentHelper.createParser(builder.bytes()); context.reset(parser); InnerHitBuilder secondInnerHits = InnerHitBuilder.fromXContent(parser, context); assertThat(innerHit, not(sameInstance(secondInnerHits))); assertThat(innerHit, equalTo(secondInnerHits)); assertThat(innerHit.hashCode(), equalTo(secondInnerHits.hashCode())); } } public void testEqualsAndHashcode() throws IOException { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { InnerHitBuilder firstInnerHit = randomInnerHits(); assertFalse("inner hit is equal to null", firstInnerHit.equals(null)); assertFalse("inner hit is equal to incompatible type", firstInnerHit.equals("")); assertTrue("inner it is not equal to self", firstInnerHit.equals(firstInnerHit)); assertThat("same inner hit's hashcode returns different values if called multiple times", firstInnerHit.hashCode(), equalTo(firstInnerHit.hashCode())); assertThat("different inner hits should not be equal", mutate(firstInnerHit), not(equalTo(firstInnerHit))); InnerHitBuilder secondBuilder = serializedCopy(firstInnerHit); assertTrue("inner hit is not equal to self", secondBuilder.equals(secondBuilder)); assertTrue("inner hit is not equal to its copy", firstInnerHit.equals(secondBuilder)); assertTrue("equals is not symmetric", secondBuilder.equals(firstInnerHit)); assertThat("inner hits copy's hashcode is different from original hashcode", secondBuilder.hashCode(), equalTo(firstInnerHit.hashCode())); InnerHitBuilder thirdBuilder = serializedCopy(secondBuilder); assertTrue("inner hit is not equal to self", thirdBuilder.equals(thirdBuilder)); assertTrue("inner hit is not equal to its copy", secondBuilder.equals(thirdBuilder)); assertThat("inner hit copy's hashcode is different from original hashcode", secondBuilder.hashCode(), equalTo(thirdBuilder.hashCode())); assertTrue("equals is not transitive", firstInnerHit.equals(thirdBuilder)); assertThat("inner hit copy's hashcode is different from original hashcode", firstInnerHit.hashCode(), equalTo(thirdBuilder.hashCode())); assertTrue("equals is not symmetric", thirdBuilder.equals(secondBuilder)); assertTrue("equals is not symmetric", thirdBuilder.equals(firstInnerHit)); } } public static InnerHitBuilder randomInnerHits() { return randomInnerHits(true); } public static InnerHitBuilder randomInnerHits(boolean recursive) { InnerHitBuilder innerHits = new InnerHitBuilder(); if (randomBoolean()) { innerHits.setNestedPath(randomAsciiOfLengthBetween(1, 16)); } else { innerHits.setParentChildType(randomAsciiOfLengthBetween(1, 16)); } innerHits.setName(randomAsciiOfLengthBetween(1, 16)); innerHits.setFrom(randomIntBetween(0, 128)); innerHits.setSize(randomIntBetween(0, 128)); innerHits.setExplain(randomBoolean()); innerHits.setVersion(randomBoolean()); innerHits.setTrackScores(randomBoolean()); innerHits.setFieldNames(randomListStuff(16, () -> randomAsciiOfLengthBetween(1, 16))); innerHits.setFieldDataFields(randomListStuff(16, () -> randomAsciiOfLengthBetween(1, 16))); innerHits.setScriptFields(randomListStuff(16, InnerHitBuilderTests::randomScript)); FetchSourceContext randomFetchSourceContext; if (randomBoolean()) { randomFetchSourceContext = new FetchSourceContext(randomBoolean()); } else { randomFetchSourceContext = new FetchSourceContext( generateRandomStringArray(12, 16, false), generateRandomStringArray(12, 16, false) ); } innerHits.setFetchSourceContext(randomFetchSourceContext); if (randomBoolean()) { innerHits.setSorts(randomListStuff(16, () -> SortBuilders.fieldSort(randomAsciiOfLengthBetween(5, 20)).order(randomFrom(SortOrder.values()))) ); } innerHits.setHighlightBuilder(HighlightBuilderTests.randomHighlighterBuilder()); if (randomBoolean()) { innerHits.setQuery(new MatchQueryBuilder(randomAsciiOfLengthBetween(1, 16), randomAsciiOfLengthBetween(1, 16))); } if (recursive && randomBoolean()) { InnerHitsBuilder innerHitsBuilder = new InnerHitsBuilder(); int size = randomIntBetween(1, 16); for (int i = 0; i < size; i++) { innerHitsBuilder.addInnerHit(randomAsciiOfLengthBetween(1, 16), randomInnerHits(false)); } innerHits.setInnerHitsBuilder(innerHitsBuilder); } return innerHits; } static InnerHitBuilder mutate(InnerHitBuilder innerHits) throws IOException { InnerHitBuilder copy = serializedCopy(innerHits); int surprise = randomIntBetween(0, 10); switch (surprise) { case 0: copy.setFrom(randomValueOtherThan(innerHits.getFrom(), () -> randomIntBetween(0, 128))); break; case 1: copy.setSize(randomValueOtherThan(innerHits.getSize(), () -> randomIntBetween(0, 128))); break; case 2: copy.setExplain(!copy.isExplain()); break; case 3: copy.setVersion(!copy.isVersion()); break; case 4: copy.setTrackScores(!copy.isTrackScores()); break; case 5: copy.setName(randomValueOtherThan(innerHits.getName(), () -> randomAsciiOfLengthBetween(1, 16))); break; case 6: copy.setFieldDataFields(randomValueOtherThan(copy.getFieldDataFields(), () -> { return randomListStuff(16, () -> randomAsciiOfLengthBetween(1, 16)); })); break; case 7: copy.setScriptFields(randomValueOtherThan(copy.getScriptFields(), () -> { return randomListStuff(16, InnerHitBuilderTests::randomScript);})); break; case 8: copy.setFetchSourceContext(randomValueOtherThan(copy.getFetchSourceContext(), () -> { FetchSourceContext randomFetchSourceContext; if (randomBoolean()) { randomFetchSourceContext = new FetchSourceContext(randomBoolean()); } else { randomFetchSourceContext = new FetchSourceContext( generateRandomStringArray(12, 16, false), generateRandomStringArray(12, 16, false) ); } return randomFetchSourceContext; })); break; case 9: copy.setSorts(randomValueOtherThan(copy.getSorts(), () -> { return randomListStuff(16, () -> SortBuilders.fieldSort(randomAsciiOfLengthBetween(5, 20)).order(randomFrom(SortOrder.values()))); })); break; case 10: copy.setHighlightBuilder(randomValueOtherThan(copy.getHighlightBuilder(), HighlightBuilderTests::randomHighlighterBuilder)); break; default: throw new IllegalStateException("unexpected surprise [" + surprise + "]"); } return copy; } static SearchSourceBuilder.ScriptField randomScript() { ScriptService.ScriptType randomScriptType = randomFrom(ScriptService.ScriptType.values()); Map<String, Object> randomMap = null; if (randomBoolean()) { randomMap = new HashMap<>(); int numEntries = randomIntBetween(0, 32); for (int i = 0; i < numEntries; i++) { randomMap.put(String.valueOf(i), randomAsciiOfLength(16)); } } Script script = new Script(randomAsciiOfLength(128), randomScriptType, randomAsciiOfLengthBetween(1, 4),randomMap); return new SearchSourceBuilder.ScriptField(randomAsciiOfLengthBetween(1, 32), script, randomBoolean()); } static <T> List<T> randomListStuff(int maxSize, Supplier<T> valueSupplier) { int size = randomIntBetween(0, maxSize); List<T> list = new ArrayList<>(size); for (int i = 0; i < size; i++) { list.add(valueSupplier.get()); } return list; } private static InnerHitBuilder serializedCopy(InnerHitBuilder original) throws IOException { try (BytesStreamOutput output = new BytesStreamOutput()) { original.writeTo(output); try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) { return new InnerHitBuilder(in); } } } }
[TEST] Make type inference simpler
core/src/test/java/org/elasticsearch/index/query/support/InnerHitBuilderTests.java
[TEST] Make type inference simpler
<ide><path>ore/src/test/java/org/elasticsearch/index/query/support/InnerHitBuilderTests.java <ide> })); <ide> break; <ide> case 9: <del> copy.setSorts(randomValueOtherThan(copy.getSorts(), () -> { <del> return randomListStuff(16, <del> () -> SortBuilders.fieldSort(randomAsciiOfLengthBetween(5, 20)).order(randomFrom(SortOrder.values()))); <del> })); <add> final List<SortBuilder<?>> sortBuilders = randomValueOtherThan(copy.getSorts(), () -> { <add> List<SortBuilder<?>> builders = randomListStuff(16, <add> () -> SortBuilders.fieldSort(randomAsciiOfLengthBetween(5, 20)).order(randomFrom(SortOrder.values()))); <add> return builders; <add> }); <add> copy.setSorts(sortBuilders); <ide> break; <ide> case 10: <ide> copy.setHighlightBuilder(randomValueOtherThan(copy.getHighlightBuilder(),
Java
apache-2.0
db1c3f2fcc1bac0c5bda06ad34e340196c863c1a
0
DV8FromTheWorld/JDA,DV8FromTheWorld/JDA
/* * Copyright 2015-2017 Austin Keener & Michael Ritter & Florian Spieß * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.dv8tion.jda.core.events.http; import net.dv8tion.jda.core.events.Event; import net.dv8tion.jda.core.requests.Request; import net.dv8tion.jda.core.requests.Response; import net.dv8tion.jda.core.requests.RestAction; import net.dv8tion.jda.core.requests.Route.CompiledRoute; import okhttp3.Headers; import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.json.JSONArray; import org.json.JSONObject; import java.util.Collections; import java.util.Set; /** * Fired when a Rest request has been executed. * * <p>Depending on the request and its result not all values have to be populated. */ public class HttpRequestEvent extends Event { private final Request<?> request; private final Response response; public HttpRequestEvent(final Request<?> request, final Response response) { super(request.getJDA()); this.request = request; this.response = response; } public Request<?> getRequest() { return this.request; } public RequestBody getRequestBody() { return this.request.getBody(); } public Object getRequestBodyRaw() { return this.request.getRawBody(); } public Headers getRequestHeaders() { return this.response == null ? null : this.response.getRawResponse() == null ? null : this.response.getRawResponse().request().headers(); } public okhttp3.Request getRequestRaw() { return this.response == null ? null : this.response.getRawResponse() == null ? null : this.response.getRawResponse().request(); } public Response getResponse() { return this.response; } public ResponseBody getResponseBody() { return this.response == null ? null : this.response.getRawResponse() == null ? null : this.response.getRawResponse().body(); } public JSONArray getResponseBodyAsArray() { return this.response == null ? null : this.response.getArray(); } public JSONObject getResponseBodyAsObject() { return this.response == null ? null : this.response.getObject(); } public String getResponseBodyAsString() { return this.response == null ? null : this.response.getString(); } public Headers getResponseHeaders() { return this.response == null ? null : this.response.getRawResponse() == null ? null : this.response.getRawResponse().headers(); } public okhttp3.Response getResponseRaw() { return this.response == null ? null : this.response.getRawResponse(); } public Set<String> getCFRays() { return this.response == null ? Collections.emptySet() : this.response.getCFRays(); } public RestAction<?> getRestAction() { return this.request.getRestAction(); } public CompiledRoute getRoute() { return this.request.getRoute(); } public boolean isRateLimit() { return this.response.isRateLimit(); } }
src/main/java/net/dv8tion/jda/core/events/http/HttpRequestEvent.java
/* * Copyright 2015-2017 Austin Keener & Michael Ritter & Florian Spieß * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.dv8tion.jda.core.events.http; import net.dv8tion.jda.core.events.Event; import net.dv8tion.jda.core.requests.Request; import net.dv8tion.jda.core.requests.Response; import net.dv8tion.jda.core.requests.RestAction; import net.dv8tion.jda.core.requests.Route.CompiledRoute; import okhttp3.Headers; import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.json.JSONArray; import org.json.JSONObject; import java.util.Collections; import java.util.Set; /** * Fired when a Rest request has been executed. * * <p>Depending on the request and its result not all values have to be populated. */ public class HttpRequestEvent extends Event { private final Request<?> request; private final Response response; public HttpRequestEvent(final Request<?> request, final Response response) { super(request.getJDA()); this.request = request; this.response = response; } public Request<?> getRequest() { return this.request; } public RequestBody getRequestBody() { return this.request.getBody(); } public Object getRequestBodyRaw() { return this.request.getRawBody(); } public Headers getRequestHeaders() { return this.response.getRawResponse().request().headers(); } public okhttp3.Request getRequestRaw() { return this.response == null ? null : this.response.getRawResponse().request(); } public Response getResponse() { return this.response; } public ResponseBody getResponseBody() { return this.response == null ? null : this.response.getRawResponse().body(); } public JSONArray getResponseBodyAsArray() { return this.response == null ? null : this.response.getArray(); } public JSONObject getResponseBodyAsObject() { return this.response == null ? null : this.response.getObject(); } public String getResponseBodyAsString() { return this.response == null ? null : this.response.getString(); } public Headers getResponseHeaders() { return this.response == null ? null : this.response.getRawResponse() == null ? null : this.response.getRawResponse().headers(); } public okhttp3.Response getResponseRaw() { return this.response == null ? null : this.response.getRawResponse(); } public Set<String> getCFRays() { return this.response == null ? Collections.emptySet() : this.response.getCFRays(); } public RestAction<?> getRestAction() { return this.request.getRestAction(); } public CompiledRoute getRoute() { return this.request.getRoute(); } public boolean isRateLimit() { return this.response.isRateLimit(); } }
Add missing null checks in HttpRequestEvent Response#rawResponse is a nullable field and some methods in the HttpRequestEvent don't treat it like it is (though some do, like HttpRequestEvent#getResponseHeaders). This adds the missing checks.
src/main/java/net/dv8tion/jda/core/events/http/HttpRequestEvent.java
Add missing null checks in HttpRequestEvent
<ide><path>rc/main/java/net/dv8tion/jda/core/events/http/HttpRequestEvent.java <ide> <ide> public Headers getRequestHeaders() <ide> { <del> return this.response.getRawResponse().request().headers(); <add> return this.response == null ? null : this.response.getRawResponse() == null ? null : this.response.getRawResponse().request().headers(); <ide> } <ide> <ide> public okhttp3.Request getRequestRaw() <ide> { <del> return this.response == null ? null : this.response.getRawResponse().request(); <add> return this.response == null ? null : this.response.getRawResponse() == null ? null : this.response.getRawResponse().request(); <ide> } <ide> <ide> public Response getResponse() <ide> <ide> public ResponseBody getResponseBody() <ide> { <del> return this.response == null ? null : this.response.getRawResponse().body(); <add> return this.response == null ? null : this.response.getRawResponse() == null ? null : this.response.getRawResponse().body(); <ide> } <ide> <ide> public JSONArray getResponseBodyAsArray()
JavaScript
apache-2.0
a9fb4a6497db9c403790e283a995b343216a4bbb
0
dimm0/scidrive-ui,dimm0/scidrive-ui,dimm0/scidrive-ui
define([ "dojo/_base/declare", "dojo/_base/lang", "dojo/_base/fx", "dojo/_base/connect", "dojo/fx", "dojo/aspect", "dojo/dom-construct", "dojo/request/xhr", "dojo/json", "dojo/io-query", "dojo/has", "dojo/sniff", "dijit/Dialog" ], function(declare, lang, fx, connect, coreFx, aspect, domConstruct, xhr, JSON, ioQuery, has, sniff, Dialog) { return declare("scidrive.SciServerLogin", null, { loginUrl: 'http://172.23.24.21/gwauth/SignIn.aspx?ReturnUrl=', logoutUrl: 'http://172.23.24.21/gwauth/SignOut.aspx?ReturnUrl=', constructor: function( /*Object*/ kwArgs) { lang.mixin(this, kwArgs); var token = ioQuery.queryToObject(dojo.doc.location.search.substr((dojo.doc.location.search[0] === "?" ? 1 : 0))).token; if("undefined" !== typeof token) { this.credentials = {token: token}; } }, loginFunc: function(identity, share) { var that = this; if (undefined == this.credentials && !this.isShare) { this.login(this); } else { require(["scidrive/ScidrivePanel"], function(ScidrivePanel) { if (undefined == dijit.byId("scidriveWidget")) { var pan = new ScidrivePanel({ id: "scidriveWidget", style: "width: 100%; height: 100%; opacity: 0;", app: that }); pan.placeAt(document.body); dijit.byId("scidriveWidget").loginToVO(that, null); // with updated credentials dijit.byId("scidriveWidget").startup(); var anim = coreFx.combine([ fx.fadeIn({ node: "scidriveWidget", duration: 1000 }), fx.fadeOut({ node: "loader", duration: 1000 }) ]).play(); aspect.after(anim, "onEnd", function() { domConstruct.destroy("loader"); }, true); } else { dijit.byId("scidriveWidget").loginToVO(that, null); // with updated credentials } }); } }, getRedirectUrl: function(baseUrl) { // Build current URL to pass it to login page var curUrl = location.protocol + '//' + location.host + location.pathname; // Append keystone token placeholder (as required by the login portal) curUrl += (curUrl.indexOf('?')>0)?'&':'?'+'token=$keystoneToken'; // Add share parameter if(this.isShare) curUrl += (curUrl.indexOf('?')>0)?'&':'?'+'share='+this.id; return baseUrl + encodeURIComponent(curUrl); }, login: function(component) { // Redirect to login page document.location.href = this.getRedirectUrl(this.loginUrl); }, logout: function(vospace, component, message) { // This is some magic I wouldn't like to touch var identity = JSON.parse(localStorage.getItem('vospace_oauth_s')); if(typeof vospace !== 'undefined') { delete identity.regions[vospace.id]; localStorage.setItem('vospace_oauth_s', JSON.stringify(identity)); delete vospace.credentials; if(vospace.isShare) { this.vospaces = this.vospaces.filter(function(curvospace, index, array) { return curvospace.id != vospace.id; }); dijit.byId("scidriveWidget").loginSelect.removeOption(vospace.id); } dijit.byId("scidriveWidget")._refreshRegions(); } // Redirect to logout page document.location.href = this.getRedirectUrl(this.logoutUrl); }, request: function(url, method, args) { var that = this; var params = this.signRequest(url, method, args); var xhrPromise = xhr(url, params); xhrPromise.then( null, function(error) { if(error.response.status == 401) { if(that.isShare) { if (typeof that.credentials === 'undefined') { // need to authenticate for the share that.login(); } else { // already authenticated, but token is either invalid or belongs to other group alert("Error: the user does not belong to share group. Logging out."); // need the proper vospace object here V that.logout(undefined, undefined, that, "User does not belong to the group requested by the share."); } } else { that.login(); } } }); return xhrPromise; }, signRequest: function(url, method, args) { var param = {}; if("undefined" !== typeof args) param = args; if("undefined" === typeof param.headers) param.headers = {}; if("undefined" !== typeof this.credentials) param.headers["X-Auth-Token"] = this.credentials.token; if(this.isShare) { param.headers["X-Share"] = this.id; console.debug(param); } param.method = method; return param; } }); });
src/scidrive/auth/SciServerLogin.js
define([ "dojo/_base/declare", "dojo/_base/lang", "dojo/_base/fx", "dojo/_base/connect", "dojo/fx", "dojo/aspect", "dojo/dom-construct", "dojo/request/xhr", "dojo/json", "dojo/io-query", "dojo/has", "dojo/sniff", "dijit/Dialog" ], function(declare, lang, fx, connect, coreFx, aspect, domConstruct, xhr, JSON, ioQuery, has, sniff, Dialog) { return declare("scidrive.SciServerLogin", null, { loginPortalUrl: 'http://zinc26.pha.jhu.edu:8082/', constructor: function( /*Object*/ kwArgs) { lang.mixin(this, kwArgs); var token = ioQuery.queryToObject(dojo.doc.location.search.substr((dojo.doc.location.search[0] === "?" ? 1 : 0))).token; if("undefined" !== typeof token) { this.credentials = {token: token}; } }, loginFunc: function(identity, share) { var that = this; if (undefined == this.credentials && !this.isShare) { this.login(this); } else { require(["scidrive/ScidrivePanel"], function(ScidrivePanel) { if (undefined == dijit.byId("scidriveWidget")) { var pan = new ScidrivePanel({ id: "scidriveWidget", style: "width: 100%; height: 100%; opacity: 0;", app: that }); pan.placeAt(document.body); dijit.byId("scidriveWidget").loginToVO(that, null); // with updated credentials dijit.byId("scidriveWidget").startup(); var anim = coreFx.combine([ fx.fadeIn({ node: "scidriveWidget", duration: 1000 }), fx.fadeOut({ node: "loader", duration: 1000 }) ]).play(); aspect.after(anim, "onEnd", function() { domConstruct.destroy("loader"); }, true); } else { dijit.byId("scidriveWidget").loginToVO(that, null); // with updated credentials } }); } }, login: function(component) { var curUrl = location.protocol + '//' + location.host + location.pathname; if(this.isShare) curUrl += encodeURIComponent((curUrl.indexOf('?')>0)?'&':'?'+ 'share='+this.id); document.location.href = this.loginPortalUrl+'?callbackUrl='+curUrl; }, logout: function(vospace, component, message) { var identity = JSON.parse(localStorage.getItem('vospace_oauth_s')); if(typeof vospace !== 'undefined') { delete identity.regions[vospace.id]; localStorage.setItem('vospace_oauth_s', JSON.stringify(identity)); delete vospace.credentials; if(vospace.isShare) { this.vospaces = this.vospaces.filter(function(curvospace, index, array) { return curvospace.id != vospace.id; }); dijit.byId("scidriveWidget").loginSelect.removeOption(vospace.id); } dijit.byId("scidriveWidget")._refreshRegions(); } document.location.href = this.loginPortalUrl+"?logout=true"+((typeof message !== 'undefined')?"&message="+message:""); }, request: function(url, method, args) { var that = this; var params = this.signRequest(url, method, args); var xhrPromise = xhr(url, params); xhrPromise.then( null, function(error) { if(error.response.status == 401) { if(that.isShare) { if (typeof that.credentials === 'undefined') { // need to authenticate for the share that.login(); } else { // already authenticated, but token is either invalid or belongs to other group alert("Error: the user does not belong to share group. Logging out."); // need the proper vospace object here V that.logout(undefined, undefined, that, "User does not belong to the group requested by the share."); } } else { that.login(); } } }); return xhrPromise; }, signRequest: function(url, method, args) { var param = {}; if("undefined" !== typeof args) param = args; if("undefined" === typeof param.headers) param.headers = {}; if("undefined" !== typeof this.credentials) param.headers["X-Auth-Token"] = this.credentials.token; if(this.isShare) { param.headers["X-Share"] = this.id; console.debug(param); } param.method = method; return param; } }); });
Modified to work with graywulf auth service.
src/scidrive/auth/SciServerLogin.js
Modified to work with graywulf auth service.
<ide><path>rc/scidrive/auth/SciServerLogin.js <ide> ], function(declare, lang, fx, connect, coreFx, aspect, domConstruct, xhr, JSON, ioQuery, has, sniff, Dialog) { <ide> return declare("scidrive.SciServerLogin", null, { <ide> <del> loginPortalUrl: 'http://zinc26.pha.jhu.edu:8082/', <add> loginUrl: 'http://172.23.24.21/gwauth/SignIn.aspx?ReturnUrl=', <add> logoutUrl: 'http://172.23.24.21/gwauth/SignOut.aspx?ReturnUrl=', <ide> <ide> constructor: function( /*Object*/ kwArgs) { <ide> lang.mixin(this, kwArgs); <ide> <ide> } <ide> }, <add> <add> getRedirectUrl: function(baseUrl) <add> { <add> // Build current URL to pass it to login page <add> var curUrl = location.protocol + '//' + location.host + location.pathname; <add> <add> // Append keystone token placeholder (as required by the login portal) <add> curUrl += (curUrl.indexOf('?')>0)?'&':'?'+'token=$keystoneToken'; <add> <add> // Add share parameter <add> if(this.isShare) <add> curUrl += (curUrl.indexOf('?')>0)?'&':'?'+'share='+this.id; <add> <add> return baseUrl + encodeURIComponent(curUrl); <add> }, <ide> <ide> login: function(component) { <del> var curUrl = location.protocol + '//' + location.host + location.pathname; <del> if(this.isShare) <del> curUrl += encodeURIComponent((curUrl.indexOf('?')>0)?'&':'?'+ <del> 'share='+this.id); <del> document.location.href = this.loginPortalUrl+'?callbackUrl='+curUrl; <add> // Redirect to login page <add> document.location.href = this.getRedirectUrl(this.loginUrl); <ide> }, <ide> <ide> logout: function(vospace, component, message) { <add> <add> // This is some magic I wouldn't like to touch <ide> var identity = JSON.parse(localStorage.getItem('vospace_oauth_s')); <ide> if(typeof vospace !== 'undefined') { <ide> delete identity.regions[vospace.id]; <ide> dijit.byId("scidriveWidget")._refreshRegions(); <ide> } <ide> <del> document.location.href = this.loginPortalUrl+"?logout=true"+((typeof message !== 'undefined')?"&message="+message:""); <add> // Redirect to logout page <add> document.location.href = this.getRedirectUrl(this.logoutUrl); <ide> }, <ide> <ide> request: function(url, method, args) {
Java
bsd-3-clause
afccbdebffeb18feeaec3c7ec4d0b50f3e42254d
0
psygate/CivModCore,psygate/CivModCore
package vg.civcraft.mc.civmodcore; import com.google.common.base.Preconditions; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.craftbukkit.libs.org.apache.commons.io.FileUtils; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; public abstract class ACivMod extends JavaPlugin { @Override public void onEnable() { // Self disable when a hard dependency is disabled registerListener(new Listener() { @EventHandler public void onPluginDisable(PluginDisableEvent event) { String pluginName = event.getPlugin().getName(); if (getDescription().getDepend().contains(pluginName)) { warning("Plugin [" + pluginName + "] has been disabled, disabling this plugin."); disable(); } } }); } @Override public void onDisable() { HandlerList.unregisterAll(this); Bukkit.getMessenger().unregisterIncomingPluginChannel(this); Bukkit.getMessenger().unregisterOutgoingPluginChannel(this); Bukkit.getScheduler().cancelTasks(this); } /** * Registers a listener class with this plugin. * * @param listener The listener class to register. */ public void registerListener(Listener listener) { if (listener == null) { throw new IllegalArgumentException("Cannot register a listener if it's null, you dummy"); } getServer().getPluginManager().registerEvents(listener, this); } /** * Determines whether this plugin is in debug mode, which is determined by a config value. * * @return Returns true if this plguin is in debug mode. */ public boolean isDebugEnabled() { return getConfig().getBoolean("debug", false); } /** * Generates a file instance based on a file within this plugin's data folder. * * @param path The path of the file relative to the data folder. * @return Returns a file instance of the generated path. */ public File getDataFile(String path) { return new File(getDataFolder(), path); } /** * Saves a default resource to the plugin's data folder if the file does not already exist. * * @param path The path to the default resource <i>AND</i> the data file. */ public void saveDefaultResource(String path) { if (!getDataFile(path).exists()) { saveResource(path, false); } } /** * Saves a particular default resource to a particular location. * * @param defaultPath The path of the file within the plugin's jar. * @param dataPath The path the file should take within the plugin's data folder. */ public void saveDefaultResourceAs(String defaultPath, String dataPath) { Preconditions.checkNotNull(defaultPath, "defaultPath cannot be null."); Preconditions.checkNotNull(dataPath, "dataPath cannot be null."); if (getDataFile(defaultPath).exists()) { return; } defaultPath = defaultPath.replace('\\', '/'); dataPath = dataPath.replace('\\', '/'); final InputStream data = getResource(defaultPath); if (data == null) { throw new IllegalArgumentException("The embedded resource '" + defaultPath + "' cannot be found in " + getFile()); } final File outFile = new File(getDataFolder(), dataPath); try { FileUtils.copyInputStreamToFile(data, outFile); } catch (IOException exception) { severe("Could not save " + outFile.getName() + " to " + outFile); exception.printStackTrace(); } } /** * Disables this plugin. */ public void disable() { getPluginLoader().disablePlugin(this); } /** * Simple SEVERE level logging. */ public void severe(String message) { getLogger().log(Level.SEVERE, message); } /** * Simple SEVERE level logging with Throwable record. */ public void severe(String message, Throwable error) { getLogger().log(Level.SEVERE, message, error); } /** * Simple WARNING level logging. */ public void warning(String message) { getLogger().log(Level.WARNING, message); } /** * Simple WARNING level logging with Throwable record. */ public void warning(String message, Throwable error) { getLogger().log(Level.WARNING, message, error); } /** * Simple WARNING level logging with ellipsis notation shortcut for defered * injection argument array. */ public void warning(String message, Object... vars) { getLogger().log(Level.WARNING, message, vars); } /** * Simple INFO level logging */ public void info(String message) { getLogger().log(Level.INFO, message); } /** * Simple INFO level logging with ellipsis notation shortcut for defered * injection argument array. */ public void info(String message, Object... vars) { getLogger().log(Level.INFO, message, vars); } /** * Live activatable debug message (using plugin's config.yml top level debug tag to decide) at * INFO level. * * Skipped if DebugLog is false. */ public void debug(String message) { if (isDebugEnabled()) { getLogger().log(Level.INFO, message); } } /** * Live activatable debug message (using plugin's config.yml top level debug tag to decide) at * INFO level with ellipsis notation shorcut for defered injection argument * array. * * Skipped if DebugLog is false. */ public void debug(String message, Object... vars) { if (isDebugEnabled()) { getLogger().log(Level.INFO, message, vars); } } /** * <p>Attempts to retrieve a plugin's instance through several known means.</p> * * <ol> * <li> * If there's an instance of the class currently enabled. (Don't request ACivMod.class, or you'll just get * the the first result. * </li> * <li>If there's a public static .getInstance() method.</li> * <li>If there's a static instance field.</li> * </ol> * * @param <T> The type of the plugin. * @param clazz The class object of the plugin. * @return Returns the first found instance of the plugin, or null. Nulls don't necessarily mean there isn't an * instance of the plugin in existence. It could just be that it's located some unexpected place. * Additionally, just because an instance has been returned does not mean that instance is enabled. */ @SuppressWarnings("unchecked") public static <T extends JavaPlugin> T getInstance(final Class<T> clazz) { if (clazz == null) { return null; } try { return JavaPlugin.getPlugin(clazz); } catch (final IllegalArgumentException | IllegalStateException ignored) { } for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { if (clazz.equals(plugin.getClass())) { return (T) plugin; } } for (final String methodName : Arrays.asList("getInstance", "getPlugin")) { try { final Method method = clazz.getDeclaredMethod(methodName); if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) && method.getParameterCount() == 0 && clazz.isAssignableFrom(method.getReturnType())) { return (T) method.invoke(null); } } catch (final Exception ignored) { } } for (final String fieldName : Arrays.asList("instance", "plugin")) { try { final Field field = clazz.getField(fieldName); if (Modifier.isStatic(field.getModifiers()) && clazz.isAssignableFrom(field.getType())) { return (T) field.get(null); } } catch (final Exception ignored) { } } // Otherwise there's no instance of the plugin, or it's stored in an unusual way return null; } }
src/main/java/vg/civcraft/mc/civmodcore/ACivMod.java
package vg.civcraft.mc.civmodcore; import com.google.common.base.Preconditions; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.craftbukkit.libs.org.apache.commons.io.FileUtils; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; public abstract class ACivMod extends JavaPlugin { @Override public void onEnable() { // Self disable when a hard dependency is disabled registerListener(new Listener() { @EventHandler public void onPluginDisable(PluginDisableEvent event) { String pluginName = event.getPlugin().getName(); if (getDescription().getDepend().contains(pluginName)) { warning("Plugin [" + pluginName + "] has been disabled, disabling this plugin."); disable(); } } }); } @Override public void onDisable() { HandlerList.unregisterAll(this); Bukkit.getMessenger().unregisterIncomingPluginChannel(this); Bukkit.getMessenger().unregisterOutgoingPluginChannel(this); Bukkit.getScheduler().cancelTasks(this); } /** * Registers a listener class with this plugin. * * @param listener The listener class to register. */ public void registerListener(Listener listener) { if (listener == null) { throw new IllegalArgumentException("Cannot register a listener if it's null, you dummy"); } getServer().getPluginManager().registerEvents(listener, this); } /** * Determines whether this plugin is in debug mode, which is determined by a config value. * * @return Returns true if this plguin is in debug mode. */ public boolean isDebugEnabled() { return getConfig().getBoolean("debug", false); } /** * Generates a file instance based on a file within this plugin's data folder. * * @param path The path of the file relative to the data folder. * @return Returns a file instance of the generated path. */ public File getDataFile(String path) { return new File(getDataFolder(), path); } /** * Saves a default resource to the plugin's data folder if the file does not already exist. * * @param path The path to the default resource <i>AND</i> the data file. */ public void saveDefaultResource(String path) { if (!getDataFile(path).exists()) { saveResource(path, false); } } /** * Saves a particular default resource to a particular location. * * @param defaultPath The path of the file within the plugin's jar. * @param dataPath The path the file should take within the plugin's data folder. */ public void saveDefaultResourceAs(String defaultPath, String dataPath) { Preconditions.checkNotNull(defaultPath, "defaultPath cannot be null."); Preconditions.checkNotNull(dataPath, "dataPath cannot be null."); if (getDataFile(defaultPath).exists()) { return; } defaultPath = defaultPath.replace('\\', '/'); dataPath = dataPath.replace('\\', '/'); final InputStream data = getResource(defaultPath); if (data == null) { throw new IllegalArgumentException("The embedded resource '" + defaultPath + "' cannot be found in " + getFile()); } final File outFile = new File(getDataFolder(), dataPath); try { FileUtils.copyInputStreamToFile(data, outFile); } catch (IOException exception) { severe("Could not save " + outFile.getName() + " to " + outFile); exception.printStackTrace(); } } /** * Disables this plugin. */ public void disable() { getPluginLoader().disablePlugin(this); } /** * Simple SEVERE level logging. */ public void severe(String message) { getLogger().log(Level.SEVERE, message); } /** * Simple SEVERE level logging with Throwable record. */ public void severe(String message, Throwable error) { getLogger().log(Level.SEVERE, message, error); } /** * Simple WARNING level logging. */ public void warning(String message) { getLogger().log(Level.WARNING, message); } /** * Simple WARNING level logging with Throwable record. */ public void warning(String message, Throwable error) { getLogger().log(Level.WARNING, message, error); } /** * Simple WARNING level logging with ellipsis notation shortcut for defered * injection argument array. */ public void warning(String message, Object... vars) { getLogger().log(Level.WARNING, message, vars); } /** * Simple INFO level logging */ public void info(String message) { getLogger().log(Level.INFO, message); } /** * Simple INFO level logging with ellipsis notation shortcut for defered * injection argument array. */ public void info(String message, Object... vars) { getLogger().log(Level.INFO, message, vars); } /** * Live activatable debug message (using plugin's config.yml top level debug tag to decide) at * INFO level. * * Skipped if DebugLog is false. */ public void debug(String message) { if (isDebugEnabled()) { getLogger().log(Level.INFO, message); } } /** * Live activatable debug message (using plugin's config.yml top level debug tag to decide) at * INFO level with ellipsis notation shorcut for defered injection argument * array. * * Skipped if DebugLog is false. */ public void debug(String message, Object... vars) { if (isDebugEnabled()) { getLogger().log(Level.INFO, message, vars); } } /** * <p>Attempts to retrieve a plugin's instance through several known means.</p> * * <ol> * <li> * If there's an instance of the class currently enabled. (Don't request ACivMod.class, or you'll just get * the the first result. * </li> * <li>If there's a public static .getInstance() method.</li> * <li>If there's a static instance field.</li> * </ol> * * @param <T> The type of the plugin. * @param clazz The class object of the plugin. * @return Returns the first found instance of the plugin, or null. Nulls don't necessarily mean there isn't an * instance of the plugin in existence. It could just be that it's located some unexpected place. Additionally, * just because an instance has been returned does not mean that instance is enabled. */ @SuppressWarnings("unchecked") public static <T extends JavaPlugin> T getInstance(final Class<T> clazz) { if (clazz == null) { return null; } try { return JavaPlugin.getPlugin(clazz); } catch (final IllegalArgumentException | IllegalStateException ignored) { } for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { if (clazz.equals(plugin.getClass())) { return (T) plugin; } } for (final String methodName : Arrays.asList("getInstance", "getPlugin")) { try { final Method method = clazz.getDeclaredMethod(methodName); if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()) && clazz.isAssignableFrom(method.getReturnType())) { return (T) method.invoke(null); } } catch (final Exception ignored) { } } for (final String fieldName : Arrays.asList("instance", "plugin")) { try { final Field field = clazz.getField(fieldName); if (Modifier.isStatic(field.getModifiers()) && clazz.isAssignableFrom(field.getType())) { return (T) field.get(null); } } catch (final Exception ignored) { } } // Otherwise there's no instance of the plugin, or it's stored in an unusual way return null; } }
Update ACivMod.getInstance()
src/main/java/vg/civcraft/mc/civmodcore/ACivMod.java
Update ACivMod.getInstance()
<ide><path>rc/main/java/vg/civcraft/mc/civmodcore/ACivMod.java <ide> * @param <T> The type of the plugin. <ide> * @param clazz The class object of the plugin. <ide> * @return Returns the first found instance of the plugin, or null. Nulls don't necessarily mean there isn't an <del> * instance of the plugin in existence. It could just be that it's located some unexpected place. Additionally, <del> * just because an instance has been returned does not mean that instance is enabled. <add> * instance of the plugin in existence. It could just be that it's located some unexpected place. <add> * Additionally, just because an instance has been returned does not mean that instance is enabled. <ide> */ <ide> @SuppressWarnings("unchecked") <ide> public static <T extends JavaPlugin> T getInstance(final Class<T> clazz) { <ide> final Method method = clazz.getDeclaredMethod(methodName); <ide> if (Modifier.isPublic(method.getModifiers()) <ide> && Modifier.isStatic(method.getModifiers()) <add> && method.getParameterCount() == 0 <ide> && clazz.isAssignableFrom(method.getReturnType())) { <ide> return (T) method.invoke(null); <ide> }
Java
mit
8e39e6d5c3003032976e8448daab237164add638
0
GMart/RSVoiP-CS374
package main; /* * Copyright (c) 2016. * By Garrett Martin (GMart on Github), * Patrick Gephart (ManualSearch), * & Matt Macke (BanishedAngel) * Class: main.Main * Last modified: 4/13/16 3:42 AM */ /** * Created by Garrett on 2/11/2016. */ import javax.sound.sampled.*; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.net.*; public class Main { static mainForm contentForm; static clientUIThread client; private static Server server; static int port = 1200; // For chatting static String Username; // User's own Name static String serverIP = "149.164.221.6"; static String userID; public static void main(String[] args) throws IOException { class serverThread implements Runnable { @Override public synchronized void run() { try { server = new Server(port); wait(100); } catch (Exception ex) { System.out.println("Error in server, could not start!"); } } } // Different from ServerThread (That has one for each connection) //RtspDecoder rtspDecoder = new RtspDecoder(); // In the future use RTP? //RtspEncoder rtspEncoder = new RtspEncoder(); // Start up server and client //(new Thread(new serverThread())).start(); client = new clientUIThread("127.0.0.1"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { contentForm = new mainForm(); } }); System.out.println("GUI set up!"); //sendIPToServer(); //(new receiveAudioThread(new ServerSocket(1201))).start(); //(new sendAudioThread(new Socket("localhost", 1201))).start(); //System.out.println("IP sent to server"); //Socket socket = new Socket("null", port); //sendAudioThread(socket); // Testing audio sending and receiving } /** * This method will connect the Buddy Server and update the IP address for the user. */ public static void sendIPToServer() throws IOException { Socket socket = null; OutputStreamWriter out; // Get public IP URL whatismyip; BufferedReader in; String ip; try { whatismyip = new URL("http://checkip.amazonaws.com"); in = new BufferedReader(new InputStreamReader( whatismyip.openStream())); ip = in.readLine(); in.close(); } catch (IOException e) { ip = InetAddress.getLocalHost().getHostAddress(); } // Craft string to send to server String str; userID = JOptionPane.showInputDialog("What is your userID?"); str = "1/" + userID + "/" + ip; String str2 = "5"; // Update your IP on server try { socket = new Socket(serverIP, 1199); out = new OutputStreamWriter(socket.getOutputStream(), "UTF-8"); out.write(str, 0, str.length()); out.write(str2, 0, str2.length()); out.close(); } catch (IOException e) { System.err.print(e); } finally { socket.close(); } } /** * @param address The new IP address to send to. * @param portNum The port to change to. */ public static void changeConnection(String address, int portNum) { port = portNum; //client = new clientUIThread(address); //TODO: Don't know why this breaks everything, should look into it! } public void sendPressed(String message) { client.processMessage(message); contentForm.clearChatText(); } public static void addChatText(String chat) { contentForm.addChat(chat); } } /** * Sends audio from the first mic to the socket, buffered. * Thread created when "Call" button pressed and no call is currently in progress. */ class sendAudioThread extends Thread { private boolean running = true; Socket socket; sendAudioThread(Socket socket) { this.socket = socket; } synchronized void setRunning(boolean running) { // Lets us control this Thread from another this.running = running; } @Override public void run() { AudioFormat audioFormat = new AudioFormat(48000, 16, 1, true, false); //Audio stream format, may tweak setRunning(true); try { socket.setTcpNoDelay(true); socket.setTrafficClass(SocketOptions.IP_TOS); socket.setPerformancePreferences(1, 5, 2); System.out.println("Setting up sending audio!"); DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat); TargetDataLine sendLine = AudioSystem.getTargetDataLine(info.getFormats()[0]); sendLine.open(audioFormat); sendLine.start(); // Opens the mic and starts to get data from it System.out.println("Opened mic"); int bufferSize = (int) audioFormat.getSampleRate() / 4;// * audioFormat.getFrameSize(); byte buffer[] = new byte[bufferSize]; BufferedOutputStream bufferedStream = new BufferedOutputStream(socket.getOutputStream(), bufferSize); System.out.println("Buffersize for sending:" + bufferSize); while (sendLine.isActive() || running) { int count = sendLine.read(buffer, 0, buffer.length); if (count > 0 || (sendLine.getLevel() > 0)) { // Arbitrary volume level (not working) to reduce bandwidth bufferedStream.write(buffer, 0, bufferSize); System.out.println("Sending audio: " + sendLine.getBufferSize() + " Level: " + sendLine.getLevel()); //System.out.println("Sending: " + Arrays.toString(buffer)); } } //bufferedStream.close(); sendLine.close(); } catch (LineUnavailableException | IOException e) { System.out.println("Error in capturing audio with connection " + socket.toString()); //e.printStackTrace(); } finally { setRunning(false); } } } /** * This class starts a thread with a ServerSocket and waits to connect, * then just plays the audio from the socket connection out of the main sound line. */ class receiveAudioThread extends Thread { private boolean running = true; private ServerSocket socket; receiveAudioThread(ServerSocket socket) { this.socket = socket; } synchronized void setRunning(boolean running) { // Lets us control this Thread from another this.running = running; } public void run() { System.out.println("Starting audio!"); AudioFormat format; format = new AudioFormat(48000, 16, 1, true, false); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); BufferedInputStream bufferedInputStream = null; SourceDataLine soundData = null; AudioInputStream inputAStream = null; try { soundData = AudioSystem.getSourceDataLine(format); // Essentially this is the speaker object soundData.open(format); System.out.println("Opened Sound"); Socket connection = socket.accept(); // Get the connection from other person bufferedInputStream = new BufferedInputStream(connection.getInputStream()); // Get Input from socket System.out.println("Received connection!!"); soundData.start(); int bufferSize = (int) format.getSampleRate() / 4;// * format.getFrameSize(); byte buffer[] = new byte[bufferSize]; try { while (soundData.isOpen() && running) { int count = bufferedInputStream.read(buffer, 0, bufferSize); if (count > 0) { soundData.write(buffer, 0, count); System.out.println("Getting audio at :" + soundData.getBufferSize()); } } bufferedInputStream.close(); // Close the stream when done } catch (IOException e) { System.out.println("Stream problem"); e.printStackTrace(); } } catch (LineUnavailableException e) { System.out.println("Line unavailable"); } catch (IOException e) { System.out.println("IO exception!"); } finally { assert soundData != null; soundData.close(); // Always close the soundLine } } } class actionCall implements ActionListener { // Fires when "Call" button is pressed. private String name; private boolean endTheCall; /** * Gets the name, ?Address?, and status of the call. First button press will start call, second will end. * * @param user The username of the person currently selected */ actionCall(User user, boolean endCall) { name = user.toString(); // Grab the name of the user endTheCall = endCall; } /** * Runs when the ActionListener on the "Call" button is pressed. * * @param e Not used here */ @Override public synchronized void actionPerformed(ActionEvent e) { sendAudioThread audioSendThread = null; // The Thread used for sending audio. Socket audioSendSocket; JOptionPane.showMessageDialog(main.mainForm.getFrames()[0], "Trying to call: " + name); if (!endTheCall) { //TODO: Initiate the call - Query and set up the correct socket, using test socket for now try { (new receiveAudioThread(new ServerSocket(1201))).start(); // Receive audio firstly audioSendSocket = new Socket("localhost", 1201); // Change localhost back to Main.serverIP audioSendThread = new sendAudioThread(audioSendSocket); audioSendThread.start();// Start that Thread } catch (IOException e1) { System.out.println("Calling or socket problem"); e1.printStackTrace(); } } else { // TODO: End the call if (audioSendThread != null && audioSendThread.isAlive()) { audioSendThread.setRunning(false); } //audioSendThread.setRunning(false); } } } class clientUIThread implements Runnable, ActionListener { private DataOutputStream dout; private DataInputStream din; private Socket socket; clientUIThread(String address) { try { // Initiate the connection InetAddress IPAddr = InetAddress.getByName(address.trim()); socket = new Socket(IPAddr, Main.port); // Grab* the streams din = new DataInputStream(socket.getInputStream()); dout = new DataOutputStream(socket.getOutputStream()); // Start a background thread for receiving messages Thread runningThread = new Thread(this); runningThread.start(); // Separated in case we need to shutdown thread in the future } catch (IOException ie) { // This will catch if the address is invalid System.out.println("Unusable IP address!\n" + ie); } } public void actionPerformed(ActionEvent e) { } /** * Gets called when the user types something * * @param message Message string to send */ void processMessage(String message) { try { if (message.trim().isEmpty()) return; // Don't send nothing // Send it to the server dout.writeUTF(message); // Clear out text input field Main.contentForm.clearChatText(); } catch (IOException ie) { ie.printStackTrace(); } } @Override public void run() { try { // Receive messages as long as it exists while (true) { // Get the message String message = din.readUTF(); // Print it to the text window Main.contentForm.addChat(message); } } catch (IOException ie) { //System.out.println(ie); } catch (Exception ex) { System.out.println("Error in client!"); } } }
src/main/Main.java
package main; /* * Copyright (c) 2016. * By Garrett Martin (GMart on Github), * Patrick Gephart (ManualSearch), * & Matt Macke (BanishedAngel) * Class: main.Main * Last modified: 4/12/16 3:48 PM */ /** * Created by Garrett on 2/11/2016. */ import javax.sound.sampled.*; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.net.*; public class Main { static mainForm contentForm; static clientUIThread client; private static Server server; static int port = 1200; // For chatting static String Username; // User's own Name static String serverIP = "149.164.221.6"; static String userID; public static void main(String[] args) throws IOException { class serverThread implements Runnable { @Override public synchronized void run() { try { server = new Server(port); wait(100); } catch (Exception ex) { System.out.println("Error in server, could not start!"); } } } // Different from ServerThread (That has one for each connection) //RtspDecoder rtspDecoder = new RtspDecoder(); // In the future use RTP? //RtspEncoder rtspEncoder = new RtspEncoder(); // Start up server and client (new Thread(new serverThread())).start(); client = new clientUIThread("localhost"); synchronized (client) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { contentForm = new mainForm(); } }); } System.out.println("GUI set up!"); //sendIPToServer(); System.out.println("IP sent to server"); //Socket socket = new Socket("null", port); //sendAudioThread(socket); // Testing audio sending and receiving } /** * This method will connect the Buddy Server and update the IP address for the user. */ public static void sendIPToServer() throws IOException { Socket socket = null; OutputStreamWriter out; // Get public IP URL whatismyip; BufferedReader in; String ip; try { whatismyip = new URL("http://checkip.amazonaws.com"); in = new BufferedReader(new InputStreamReader( whatismyip.openStream())); ip = in.readLine(); in.close(); } catch (IOException e) { ip = InetAddress.getLocalHost().getHostAddress(); } // Craft string to send to server String str; userID = JOptionPane.showInputDialog("What is your userID?"); str = "1/" + userID + "/" + ip; String str2 = "5"; // Update your IP on server try { socket = new Socket(serverIP, 1199); out = new OutputStreamWriter(socket.getOutputStream(), "UTF-8"); out.write(str, 0, str.length()); out.write(str2, 0, str2.length()); out.close(); } catch (IOException e) { System.err.print(e); } finally { socket.close(); } } /** * @param address The new IP address to send to. * @param portNum The port to change to. */ public static void changeConnection(String address, int portNum) { port = portNum; //client = new clientUIThread(address); //TODO: Don't know why this breaks everything, should look into it! } /** * Play audio - TODO: Modify to receive a socket parameter and play that directly * * @param audioClip Audio to play */ static void startPlayingAudio(ServerSocket socket) { AudioFormat format; TargetDataLine targetDataLine; format = new AudioFormat(16000, 16, 1, true, false); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); BufferedInputStream bufferedInputStream = null; SourceDataLine soundData = null; try { //targetDataLine = AudioSystem.getTargetDataLine(format); soundData = AudioSystem.getSourceDataLine(format); soundData.open(format); //targetDataLine.open(format); bufferedInputStream = new BufferedInputStream(socket.accept().getInputStream()); } catch (LineUnavailableException e) { System.out.println("Line unavailable"); } catch (IOException e) { System.out.println("IO exception!"); } byte buffer[] = new byte[512]; try { while (bufferedInputStream.available() > 0) { int count = bufferedInputStream.read(buffer, 0, 512); if (count > 0) { soundData.write(buffer, 0, 512); } } bufferedInputStream.close(); // Close the stream when done } catch (IOException e) { System.out.println("Stream problem"); e.printStackTrace(); } finally { soundData.close(); // Always close the microphone } } public void sendPressed(String message) { client.processMessage(message); contentForm.clearChatText(); } public static void addChatText(String chat) { contentForm.addChat(chat); } } /** * Sends audio from the first mic to the socket, buffered. * Thread created when "Call" button pressed and no call is currently in progress. */ class sendAudioThread extends Thread { private boolean running = true; Socket socket; sendAudioThread(Socket socket) { this.socket = socket; } public synchronized void setRunning(boolean running) { // Lets us control this Thread from another this.running = running; } @Override public void run() { AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true, false); //Audio stream format, may tweak setRunning(true); try { socket.setTcpNoDelay(true); socket.setTrafficClass(SocketOptions.IP_TOS); socket.setPerformancePreferences(1, 5, 2); DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat); TargetDataLine sendLine = (TargetDataLine) AudioSystem.getLine(info); sendLine.open(audioFormat); sendLine.start(); int bufferSize = (int) audioFormat.getSampleRate() * audioFormat.getFrameSize() * 2; byte buffer[] = new byte[bufferSize]; BufferedOutputStream bufferedStream = new BufferedOutputStream(socket.getOutputStream(), bufferSize); while (sendLine.isRunning() && running) { int count = sendLine.read(buffer, 0, buffer.length); if (count > 0 && (sendLine.getLevel() > 0.01)) { // Arbitrary volume level to reduce bandwidth bufferedStream.write(buffer, 0, count); InputStream input = new ByteArrayInputStream(buffer); final AudioInputStream ais = new AudioInputStream(input, audioFormat, buffer.length / audioFormat.getFrameSize()); } } bufferedStream.close(); } catch (LineUnavailableException | IOException e) { System.out.println("Error in capturing audio with connection " + socket.toString()); //e.printStackTrace(); } } } class receiveAudioThread extends Thread { private boolean running = true; Socket socket; public void run() { try { Main.startPlayingAudio(new ServerSocket(1201)); } catch (IOException e) { e.printStackTrace(); } } } class actionCall implements ActionListener { // Fires when "Call" button is pressed. private String name; private boolean endTheCall; /** * Gets the name, ?Address?, and status of the call. First button press will start call, second will end. * * @param user The username of the person currently selected */ actionCall(User user, boolean endCall) { name = user.toString(); // Grab the name of the user endTheCall = endCall; } /** * Runs when the ActionListener on the "Call" button is pressed. * * @param e Not used here */ @Override public synchronized void actionPerformed(ActionEvent e) { sendAudioThread audioSendThread = null; // The Thread used for sending audio. Socket audioSendSocket; JOptionPane.showMessageDialog(main.mainForm.getFrames()[0], "Trying to call: " + name); if (!endTheCall) { //TODO: Initiate the call - Query and set up the correct socket, using test socket for now try { (new receiveAudioThread()).start(); audioSendSocket = new Socket("localhost", 1201); audioSendThread = new sendAudioThread(audioSendSocket); audioSendThread.start();// Start that Thread } catch (IOException e1) { System.out.println("Calling or socket problem"); e1.printStackTrace(); } } else { // TODO: End the call if (audioSendThread == null || audioSendThread.isAlive()) { audioSendThread.setRunning(false); } //audioSendThread.setRunning(false); } } } class clientUIThread implements Runnable, ActionListener { private DataOutputStream dout; private DataInputStream din; private Socket socket; clientUIThread(String address) { try { // Initiate the connection InetAddress IPAddr = InetAddress.getByName(address.trim()); socket = new Socket(IPAddr, Main.port); // Grab* the streams din = new DataInputStream(socket.getInputStream()); dout = new DataOutputStream(socket.getOutputStream()); // Start a background thread for receiving messages Thread runningThread = new Thread(this); runningThread.start(); // Separated in case we need to shutdown thread in the future } catch (IOException ie) { // This will catch if the address is invalid System.out.println("Unusable IP address!\n" + ie); } } public void actionPerformed(ActionEvent e) { } /** * Gets called when the user types something * * @param message Message string to send */ void processMessage(String message) { try { if (message.trim().isEmpty()) return; // Don't send nothing // Send it to the server dout.writeUTF(message); // Clear out text input field Main.contentForm.clearChatText(); } catch (IOException ie) { ie.printStackTrace(); } } @Override public void run() { try { // Receive messages as long as it exists while (true) { // Get the message String message = din.readUTF(); // Print it to the text window Main.contentForm.addChat(message); } } catch (IOException ie) { //System.out.println(ie); } catch (Exception ex) { System.out.println("Error in client!"); } } }
Got Audio to both send and receive! It echos back to me, at least locally. It was the part where I checked the sound level that was the problem. Also the bufferSize was wrong on the receive end. Refactored receiveAudioThread.
src/main/Main.java
Got Audio to both send and receive! It echos back to me, at least locally. It was the part where I checked the sound level that was the problem. Also the bufferSize was wrong on the receive end. Refactored receiveAudioThread.
<ide><path>rc/main/Main.java <ide> * Patrick Gephart (ManualSearch), <ide> * & Matt Macke (BanishedAngel) <ide> * Class: main.Main <del> * Last modified: 4/12/16 3:48 PM <add> * Last modified: 4/13/16 3:42 AM <ide> */ <ide> <ide> /** <ide> //RtspDecoder rtspDecoder = new RtspDecoder(); // In the future use RTP? <ide> //RtspEncoder rtspEncoder = new RtspEncoder(); <ide> // Start up server and client <del> (new Thread(new serverThread())).start(); <del> <del> client = new clientUIThread("localhost"); <del> <del> synchronized (client) { <del> SwingUtilities.invokeLater(new Runnable() { <del> @Override <del> public void run() { <del> contentForm = new mainForm(); <del> } <del> }); <del> } <add> //(new Thread(new serverThread())).start(); <add> <add> client = new clientUIThread("127.0.0.1"); <add> <add> SwingUtilities.invokeLater(new Runnable() { <add> @Override <add> public void run() { <add> contentForm = new mainForm(); <add> } <add> }); <add> <ide> <ide> System.out.println("GUI set up!"); <ide> <ide> //sendIPToServer(); <del> <del> <del> System.out.println("IP sent to server"); <add> //(new receiveAudioThread(new ServerSocket(1201))).start(); <add> //(new sendAudioThread(new Socket("localhost", 1201))).start(); <add> <add> //System.out.println("IP sent to server"); <ide> <ide> //Socket socket = new Socket("null", port); <ide> //sendAudioThread(socket); // Testing audio sending and receiving <ide> <ide> } <ide> <del> /** <del> * Play audio - TODO: Modify to receive a socket parameter and play that directly <del> * <del> * @param audioClip Audio to play <del> */ <del> static void startPlayingAudio(ServerSocket socket) { <del> AudioFormat format; <del> TargetDataLine targetDataLine; <del> format = new AudioFormat(16000, 16, 1, true, false); <del> DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); <del> BufferedInputStream bufferedInputStream = null; <del> SourceDataLine soundData = null; <del> try { <del> //targetDataLine = AudioSystem.getTargetDataLine(format); <del> soundData = AudioSystem.getSourceDataLine(format); <del> soundData.open(format); <del> //targetDataLine.open(format); <del> bufferedInputStream = new BufferedInputStream(socket.accept().getInputStream()); <del> <del> } catch (LineUnavailableException e) { <del> System.out.println("Line unavailable"); <del> <del> } catch (IOException e) { <del> System.out.println("IO exception!"); <del> <del> } <del> byte buffer[] = new byte[512]; <del> try { <del> while (bufferedInputStream.available() > 0) { <del> int count = bufferedInputStream.read(buffer, 0, 512); <del> if (count > 0) { <del> soundData.write(buffer, 0, 512); <del> } <del> } <del> bufferedInputStream.close(); // Close the stream when done <del> } catch (IOException e) { <del> System.out.println("Stream problem"); <del> e.printStackTrace(); <del> } finally { <del> soundData.close(); // Always close the microphone <del> } <del> <del> } <del> <ide> public void sendPressed(String message) { <ide> client.processMessage(message); <ide> contentForm.clearChatText(); <ide> this.socket = socket; <ide> } <ide> <del> public synchronized void setRunning(boolean running) { // Lets us control this Thread from another <add> synchronized void setRunning(boolean running) { // Lets us control this Thread from another <ide> this.running = running; <ide> } <ide> <ide> @Override <ide> public void run() { <del> AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true, false); //Audio stream format, may tweak <add> AudioFormat audioFormat = new AudioFormat(48000, 16, 1, true, false); //Audio stream format, may tweak <ide> setRunning(true); <ide> try { <ide> socket.setTcpNoDelay(true); <ide> socket.setTrafficClass(SocketOptions.IP_TOS); <ide> socket.setPerformancePreferences(1, 5, 2); <del> <add> System.out.println("Setting up sending audio!"); <ide> <ide> DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat); <del> TargetDataLine sendLine = (TargetDataLine) AudioSystem.getLine(info); <add> TargetDataLine sendLine = AudioSystem.getTargetDataLine(info.getFormats()[0]); <ide> sendLine.open(audioFormat); <del> sendLine.start(); <del> int bufferSize = (int) audioFormat.getSampleRate() * audioFormat.getFrameSize() * 2; <add> sendLine.start(); // Opens the mic and starts to get data from it <add> System.out.println("Opened mic"); <add> int bufferSize = (int) audioFormat.getSampleRate() / 4;// * audioFormat.getFrameSize(); <ide> byte buffer[] = new byte[bufferSize]; <ide> BufferedOutputStream bufferedStream = new BufferedOutputStream(socket.getOutputStream(), bufferSize); <del> while (sendLine.isRunning() && running) { <add> System.out.println("Buffersize for sending:" + bufferSize); <add> while (sendLine.isActive() || running) { <ide> int count = sendLine.read(buffer, 0, buffer.length); <del> if (count > 0 && (sendLine.getLevel() > 0.01)) { // Arbitrary volume level to reduce bandwidth <del> bufferedStream.write(buffer, 0, count); <del> InputStream input = new ByteArrayInputStream(buffer); <del> final AudioInputStream ais = new AudioInputStream(input, audioFormat, buffer.length / audioFormat.getFrameSize()); <add> if (count > 0 || (sendLine.getLevel() > 0)) { // Arbitrary volume level (not working) to reduce bandwidth <add> bufferedStream.write(buffer, 0, bufferSize); <add> System.out.println("Sending audio: " + sendLine.getBufferSize() + " Level: " + sendLine.getLevel()); <add> //System.out.println("Sending: " + Arrays.toString(buffer)); <ide> <ide> } <ide> } <del> bufferedStream.close(); <add> //bufferedStream.close(); <add> sendLine.close(); <ide> <ide> } catch (LineUnavailableException | IOException e) { <ide> System.out.println("Error in capturing audio with connection " + socket.toString()); <ide> //e.printStackTrace(); <del> } <del> } <del>} <del> <add> } finally { <add> setRunning(false); <add> } <add> } <add>} <add> <add>/** <add> * This class starts a thread with a ServerSocket and waits to connect, <add> * then just plays the audio from the socket connection out of the main sound line. <add> */ <ide> class receiveAudioThread extends Thread { <ide> private boolean running = true; <del> Socket socket; <add> private ServerSocket socket; <add> <add> receiveAudioThread(ServerSocket socket) { <add> this.socket = socket; <add> <add> } <add> <add> synchronized void setRunning(boolean running) { // Lets us control this Thread from another <add> this.running = running; <add> } <ide> <ide> public void run() { <del> try { <del> Main.startPlayingAudio(new ServerSocket(1201)); <add> System.out.println("Starting audio!"); <add> AudioFormat format; <add> format = new AudioFormat(48000, 16, 1, true, false); <add> DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); <add> BufferedInputStream bufferedInputStream = null; <add> SourceDataLine soundData = null; <add> AudioInputStream inputAStream = null; <add> try { <add> soundData = AudioSystem.getSourceDataLine(format); // Essentially this is the speaker object <add> soundData.open(format); <add> System.out.println("Opened Sound"); <add> Socket connection = socket.accept(); // Get the connection from other person <add> bufferedInputStream = new BufferedInputStream(connection.getInputStream()); // Get Input from socket <add> System.out.println("Received connection!!"); <add> soundData.start(); <add> int bufferSize = (int) format.getSampleRate() / 4;// * format.getFrameSize(); <add> byte buffer[] = new byte[bufferSize]; <add> try { <add> while (soundData.isOpen() && running) { <add> int count = bufferedInputStream.read(buffer, 0, bufferSize); <add> if (count > 0) { <add> soundData.write(buffer, 0, count); <add> System.out.println("Getting audio at :" + soundData.getBufferSize()); <add> } <add> } <add> bufferedInputStream.close(); // Close the stream when done <add> } catch (IOException e) { <add> System.out.println("Stream problem"); <add> e.printStackTrace(); <add> } <add> } catch (LineUnavailableException e) { <add> System.out.println("Line unavailable"); <ide> } catch (IOException e) { <del> e.printStackTrace(); <del> } <add> System.out.println("IO exception!"); <add> } finally { <add> assert soundData != null; <add> soundData.close(); // Always close the soundLine <add> } <add> <ide> } <ide> } <ide> <ide> if (!endTheCall) { <ide> //TODO: Initiate the call - Query and set up the correct socket, using test socket for now <ide> try { <del> (new receiveAudioThread()).start(); <del> audioSendSocket = new Socket("localhost", 1201); <add> (new receiveAudioThread(new ServerSocket(1201))).start(); // Receive audio firstly <add> audioSendSocket = new Socket("localhost", 1201); // Change localhost back to Main.serverIP <ide> audioSendThread = new sendAudioThread(audioSendSocket); <ide> <ide> audioSendThread.start();// Start that Thread <ide> } <ide> } else { <ide> // TODO: End the call <del> if (audioSendThread == null || audioSendThread.isAlive()) { <add> if (audioSendThread != null && audioSendThread.isAlive()) { <ide> audioSendThread.setRunning(false); <ide> } <ide> //audioSendThread.setRunning(false);
Java
apache-2.0
4fb86f76a23f6105c4e62aa012a1dca9400292c0
0
osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi
/* * $Date$ * * Copyright (c) OSGi Alliance (2002, 2008). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.util.xml; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.SAXParserFactory; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceFactory; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; /** * A BundleActivator class that allows any JAXP compliant XML Parser to register * itself as an OSGi parser service. * * Multiple JAXP compliant parsers can concurrently register by using this * BundleActivator class. Bundles who wish to use an XML parser can then use the * framework's service registry to locate available XML Parsers with the desired * characteristics such as validating and namespace-aware. * * <p> * The services that this bundle activator enables a bundle to provide are: * <ul> * <li><code>javax.xml.parsers.SAXParserFactory</code>({@link #SAXFACTORYNAME}) * <li><code>javax.xml.parsers.DocumentBuilderFactory</code>( * {@link #DOMFACTORYNAME}) * </ul> * * <p> * The algorithm to find the implementations of the abstract parsers is derived * from the JAR file specifications, specifically the Services API. * <p> * An XMLParserActivator assumes that it can find the class file names of the * factory classes in the following files: * <ul> * <li><code>/META-INF/services/javax.xml.parsers.SAXParserFactory</code> is a * file contained in a jar available to the runtime which contains the * implementation class name(s) of the SAXParserFactory. * <li><code>/META-INF/services/javax.xml.parsers.DocumentBuilderFactory</code> * is a file contained in a jar available to the runtime which contains the * implementation class name(s) of the <code>DocumentBuilderFactory</code> * </ul> * <p> * If either of the files does not exist, <code>XMLParserActivator</code> * assumes that the parser does not support that parser type. * * <p> * <code>XMLParserActivator</code> attempts to instantiate both the * <code>SAXParserFactory</code> and the <code>DocumentBuilderFactory</code>. It * registers each factory with the framework along with service properties: * <ul> * <li>{@link #PARSER_VALIDATING}- indicates if this factory supports validating * parsers. It's value is a <code>Boolean</code>. * <li>{@link #PARSER_NAMESPACEAWARE}- indicates if this factory supports * namespace aware parsers It's value is a <code>Boolean</code>. * </ul> * <p> * Individual parser implementations may have additional features, properties, * or attributes which could be used to select a parser with a filter. These can * be added by extending this class and overriding the * <code>setSAXProperties</code> and <code>setDOMProperties</code> methods. * * @ThreadSafe * @version $Revision$ */ public class XMLParserActivator implements BundleActivator, ServiceFactory { /** Context of this bundle */ private volatile BundleContext context; /** * Filename containing the SAX Parser Factory Class name. Also used as the * basis for the <code>SERVICE_PID<code> registration property. */ public static final String SAXFACTORYNAME = "javax.xml.parsers.SAXParserFactory"; /** * Filename containing the DOM Parser Factory Class name. Also used as the * basis for the <code>SERVICE_PID</code> registration property. */ public static final String DOMFACTORYNAME = "javax.xml.parsers.DocumentBuilderFactory"; /** Path to the factory class name files */ private static final String PARSERCLASSFILEPATH = "/META-INF/services/"; /** Fully qualified path name of SAX Parser Factory Class Name file */ public static final String SAXCLASSFILE = PARSERCLASSFILEPATH + SAXFACTORYNAME; /** Fully qualified path name of DOM Parser Factory Class Name file */ public static final String DOMCLASSFILE = PARSERCLASSFILEPATH + DOMFACTORYNAME; /** SAX Factory Service Description */ private static final String SAXFACTORYDESCRIPTION = "A JAXP Compliant SAX Parser"; /** DOM Factory Service Description */ private static final String DOMFACTORYDESCRIPTION = "A JAXP Compliant DOM Parser"; /** * Service property specifying if factory is configured to support * validating parsers. The value is of type <code>Boolean</code>. */ public static final String PARSER_VALIDATING = "parser.validating"; /** * Service property specifying if factory is configured to support namespace * aware parsers. The value is of type <code>Boolean</code>. */ public static final String PARSER_NAMESPACEAWARE = "parser.namespaceAware"; /** * Key for parser factory name property - this must be saved in the parsers * properties hashtable so that the parser factory can be instantiated from * a ServiceReference */ private static final String FACTORYNAMEKEY = "parser.factoryname"; /** * Called when this bundle is started so the Framework can perform the * bundle-specific activities necessary to start this bundle. This method * can be used to register services or to allocate any resources that this * bundle needs. * * <p> * This method must complete and return to its caller in a timely manner. * * <p> * This method attempts to register a SAX and DOM parser with the * Framework's service registry. * * @param context The execution context of the bundle being started. * @throws java.lang.Exception If this method throws an exception, this * bundle is marked as stopped and the Framework will remove this * bundle's listeners, unregister all services registered by this * bundle, and release all services used by this bundle. */ public void start(BundleContext context) throws Exception { this.context = context; Bundle parserBundle = context.getBundle(); try { // check for sax parsers registerSAXParsers(getParserFactoryClassNames(parserBundle .getResource(SAXCLASSFILE))); // check for dom parsers registerDOMParsers(getParserFactoryClassNames(parserBundle .getResource(DOMCLASSFILE))); } catch (IOException ioe) { // if there were any IO errors accessing the resource files // containing the class names ioe.printStackTrace(); throw new FactoryConfigurationError(ioe); } } /** * This method has nothing to do as all active service registrations will * automatically get unregistered when the bundle stops. * * @param context The execution context of the bundle being stopped. * @throws java.lang.Exception If this method throws an exception, the * bundle is still marked as stopped, and the Framework will remove * the bundle's listeners, unregister all services registered by the * bundle, and release all services used by the bundle. */ public void stop(BundleContext context) throws Exception { // framework will automatically unregister the parser services } /** * Given the URL for a file, reads and returns the parser class names. There * may be multiple classes specified in this file, one per line. There may * also be comment lines in the file, which begin with "#". * * @param parserUrl The URL of the service file containing the parser class * names * @return A vector of strings containing the parser class names or null if * parserUrl is null * @throws IOException if there is a problem reading the URL input stream */ private Vector getParserFactoryClassNames(URL parserUrl) throws IOException { Vector v = new Vector(1); if (parserUrl != null) { String parserFactoryClassName = null; InputStream is = parserUrl.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); while (true) { parserFactoryClassName = br.readLine(); if (parserFactoryClassName == null) { break; // end of file reached } String pfcName = parserFactoryClassName.trim(); if (pfcName.length() == 0) { continue; // blank line } int commentIdx = pfcName.indexOf("#"); if (commentIdx == 0) { // comment line continue; } else if (commentIdx < 0) { // no comment on this line v.addElement(pfcName); } else { v.addElement(pfcName.substring(0, commentIdx).trim()); } } return v; } else { return null; } } /** * Register SAX Parser Factory Services with the framework. * * @param parserFactoryClassNames - a <code>Vector</code> of * <code>String</code> objects containing the names of the parser * Factory Classes * @throws FactoryConfigurationError if thrown from <code>getFactory</code> */ private void registerSAXParsers(Vector parserFactoryClassNames) throws FactoryConfigurationError { if (parserFactoryClassNames != null) { Enumeration e = parserFactoryClassNames.elements(); int index = 0; while (e.hasMoreElements()) { String parserFactoryClassName = (String) e.nextElement(); // create a sax parser factory just to get it's default // properties. It will never be used since // this class will operate as a service factory and give each // service requestor it's own SaxParserFactory SAXParserFactory factory = (SAXParserFactory) getFactory(parserFactoryClassName); Hashtable properties = new Hashtable(7); // figure out the default properties of the parser setDefaultSAXProperties(factory, properties, index); // store the parser factory class name in the properties so that // it can be retrieved when getService is called // to return a parser factory properties.put(FACTORYNAMEKEY, parserFactoryClassName); // release the factory factory = null; // register the factory as a service context.registerService(SAXFACTORYNAME, this, properties); index++; } } } /** * <p> * Set the SAX Parser Service Properties. By default, the following * properties are set: * <ul> * <li><code>SERVICE_DESCRIPTION</code> * <li><code>SERVICE_PID</code> * <li><code>PARSER_VALIDATING</code>- instantiates a parser and queries * it to find out whether it is validating or not * <li><code>PARSER_NAMESPACEAWARE</code>- instantiates a parser and * queries it to find out whether it is namespace aware or not * <ul> * * @param factory The <code>SAXParserFactory</code> object * @param props <code>Hashtable</code> of service properties. */ private void setDefaultSAXProperties(SAXParserFactory factory, Hashtable props, int index) { props.put(Constants.SERVICE_DESCRIPTION, SAXFACTORYDESCRIPTION); props.put(Constants.SERVICE_PID, SAXFACTORYNAME + "." + context.getBundle().getBundleId() + "." + index); setSAXProperties(factory, props); } /** * <p> * Set the customizable SAX Parser Service Properties. * * <p> * This method attempts to instantiate a validating parser and a namespace * aware parser to determine if the parser can support those features. The * appropriate properties are then set in the specified properties object. * * <p> * This method can be overridden to add additional SAX2 features and * properties. If you want to be able to filter searches of the OSGi service * registry, this method must put a key, value pair into the properties * object for each feature or property. For example, * * properties.put("http://www.acme.com/features/foo", Boolean.TRUE); * * @param factory - the SAXParserFactory object * @param properties - the properties object for the service */ public void setSAXProperties(SAXParserFactory factory, Hashtable properties) { // check if this parser can be configured to validate boolean validating = true; factory.setValidating(true); factory.setNamespaceAware(false); try { factory.newSAXParser(); } catch (Exception pce_val) { validating = false; } // check if this parser can be configured to be namespaceaware boolean namespaceaware = true; factory.setValidating(false); factory.setNamespaceAware(true); try { factory.newSAXParser(); } catch (Exception pce_nsa) { namespaceaware = false; } // set the factory values factory.setValidating(validating); factory.setNamespaceAware(namespaceaware); // set the OSGi service properties properties.put(PARSER_NAMESPACEAWARE, new Boolean(namespaceaware)); properties.put(PARSER_VALIDATING, new Boolean(validating)); } /** * Register DOM Parser Factory Services with the framework. * * @param parserFactoryClassNames - a <code>Vector</code> of * <code>String</code> objects containing the names of the parser * Factory Classes * @throws FactoryConfigurationError if thrown from <code>getFactory</code> */ private void registerDOMParsers(Vector parserFactoryClassNames) throws FactoryConfigurationError { if (parserFactoryClassNames != null) { Enumeration e = parserFactoryClassNames.elements(); int index = 0; while (e.hasMoreElements()) { String parserFactoryClassName = (String) e.nextElement(); // create a dom parser factory just to get it's default // properties. It will never be used since // this class will operate as a service factory and give each // service requestor it's own DocumentBuilderFactory DocumentBuilderFactory factory = (DocumentBuilderFactory) getFactory(parserFactoryClassName); Hashtable properties = new Hashtable(7); // figure out the default properties of the parser setDefaultDOMProperties(factory, properties, index); // store the parser factory class name in the properties so that // it can be retrieved when getService is called // to return a parser factory properties.put(FACTORYNAMEKEY, parserFactoryClassName); // release the factory factory = null; // register the factory as a service context.registerService(DOMFACTORYNAME, this, properties); index++; } } } /** * Set the DOM parser service properties. * * By default, the following properties are set: * <ul> * <li><code>SERVICE_DESCRIPTION</code> * <li><code>SERVICE_PID</code> * <li><code>PARSER_VALIDATING</code> * <li><code>PARSER_NAMESPACEAWARE</code> * <ul> * * @param factory The <code>DocumentBuilderFactory</code> object * @param props <code>Hashtable</code> of service properties. */ private void setDefaultDOMProperties(DocumentBuilderFactory factory, Hashtable props, int index) { props.put(Constants.SERVICE_DESCRIPTION, DOMFACTORYDESCRIPTION); props.put(Constants.SERVICE_PID, DOMFACTORYNAME + "." + context.getBundle().getBundleId() + "." + index); setDOMProperties(factory, props); } /** * <p> * Set the customizable DOM Parser Service Properties. * * <p> * This method attempts to instantiate a validating parser and a namespace * aware parser to determine if the parser can support those features. The * appropriate properties are then set in the specified props object. * * <p> * This method can be overridden to add additional DOM2 features and * properties. If you want to be able to filter searches of the OSGi service * registry, this method must put a key, value pair into the properties * object for each feature or property. For example, * * properties.put("http://www.acme.com/features/foo", Boolean.TRUE); * * @param factory - the DocumentBuilderFactory object * @param props - Hashtable of service properties. */ public void setDOMProperties(DocumentBuilderFactory factory, Hashtable props) { // check if this parser can be configured to validate boolean validating = true; factory.setValidating(true); factory.setNamespaceAware(false); try { factory.newDocumentBuilder(); } catch (Exception pce_val) { validating = false; } // check if this parser can be configured to be namespaceaware boolean namespaceaware = true; factory.setValidating(false); factory.setNamespaceAware(true); try { factory.newDocumentBuilder(); } catch (Exception pce_nsa) { namespaceaware = false; } // set the factory values factory.setValidating(validating); factory.setNamespaceAware(namespaceaware); // set the OSGi service properties props.put(PARSER_VALIDATING, new Boolean(validating)); props.put(PARSER_NAMESPACEAWARE, new Boolean(namespaceaware)); } /** * Given a parser factory class name, instantiate that class. * * @param parserFactoryClassName A <code>String</code> object containing * the name of the parser factory class * @return a parserFactoryClass Object * @pre parserFactoryClassName!=null */ private Object getFactory(String parserFactoryClassName) throws FactoryConfigurationError { Exception e = null; try { return context.getBundle().loadClass(parserFactoryClassName) .newInstance(); } catch (ClassNotFoundException cnfe) { e = cnfe; } catch (InstantiationException ie) { e = ie; } catch (IllegalAccessException iae) { e = iae; } throw new FactoryConfigurationError(e); } /** * Creates a new XML Parser Factory object. * * <p> * A unique XML Parser Factory object is returned for each call to this * method. * * <p> * The returned XML Parser Factory object will be configured for validating * and namespace aware support as specified in the service properties of the * specified ServiceRegistration object. * * This method can be overridden to configure additional features in the * returned XML Parser Factory object. * * @param bundle The bundle using the service. * @param registration The <code>ServiceRegistration</code> object for the * service. * @return A new, configured XML Parser Factory object or null if a * configuration error was encountered */ public Object getService(Bundle bundle, ServiceRegistration registration) { ServiceReference sref = registration.getReference(); String parserFactoryClassName = (String) sref .getProperty(FACTORYNAMEKEY); try { // need to set factory properties Object factory = getFactory(parserFactoryClassName); if (factory instanceof SAXParserFactory) { ((SAXParserFactory) factory).setValidating(((Boolean) sref .getProperty(PARSER_VALIDATING)).booleanValue()); ((SAXParserFactory) factory).setNamespaceAware(((Boolean) sref .getProperty(PARSER_NAMESPACEAWARE)).booleanValue()); } else if (factory instanceof DocumentBuilderFactory) { ((DocumentBuilderFactory) factory) .setValidating(((Boolean) sref .getProperty(PARSER_VALIDATING)) .booleanValue()); ((DocumentBuilderFactory) factory) .setNamespaceAware(((Boolean) sref .getProperty(PARSER_NAMESPACEAWARE)) .booleanValue()); } return factory; } catch (FactoryConfigurationError fce) { fce.printStackTrace(); return null; } } /** * Releases a XML Parser Factory object. * * @param bundle The bundle releasing the service. * @param registration The <code>ServiceRegistration</code> object for the * service. * @param service The XML Parser Factory object returned by a previous call * to the <code>getService</code> method. */ public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) { } }
org.osgi.util.xml/src/org/osgi/util/xml/XMLParserActivator.java
/* * $Date$ * * Copyright (c) OSGi Alliance (2002, 2008). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.util.xml; import java.io.*; import java.net.URL; import java.util.*; import javax.xml.parsers.*; import org.osgi.framework.*; /** * A BundleActivator class that allows any JAXP compliant XML Parser to register * itself as an OSGi parser service. * * Multiple JAXP compliant parsers can concurrently register by using this * BundleActivator class. Bundles who wish to use an XML parser can then use the * framework's service registry to locate available XML Parsers with the desired * characteristics such as validating and namespace-aware. * * <p> * The services that this bundle activator enables a bundle to provide are: * <ul> * <li><code>javax.xml.parsers.SAXParserFactory</code>({@link #SAXFACTORYNAME}) * <li><code>javax.xml.parsers.DocumentBuilderFactory</code>( * {@link #DOMFACTORYNAME}) * </ul> * * <p> * The algorithm to find the implementations of the abstract parsers is derived * from the JAR file specifications, specifically the Services API. * <p> * An XMLParserActivator assumes that it can find the class file names of the * factory classes in the following files: * <ul> * <li><code>/META-INF/services/javax.xml.parsers.SAXParserFactory</code> is * a file contained in a jar available to the runtime which contains the * implementation class name(s) of the SAXParserFactory. * <li><code>/META-INF/services/javax.xml.parsers.DocumentBuilderFactory</code> * is a file contained in a jar available to the runtime which contains the * implementation class name(s) of the <code>DocumentBuilderFactory</code> * </ul> * <p> * If either of the files does not exist, <code>XMLParserActivator</code> * assumes that the parser does not support that parser type. * * <p> * <code>XMLParserActivator</code> attempts to instantiate both the * <code>SAXParserFactory</code> and the <code>DocumentBuilderFactory</code>. * It registers each factory with the framework along with service properties: * <ul> * <li>{@link #PARSER_VALIDATING}- indicates if this factory supports * validating parsers. It's value is a <code>Boolean</code>. * <li>{@link #PARSER_NAMESPACEAWARE}- indicates if this factory supports * namespace aware parsers It's value is a <code>Boolean</code>. * </ul> * <p> * Individual parser implementations may have additional features, properties, * or attributes which could be used to select a parser with a filter. These can * be added by extending this class and overriding the * <code>setSAXProperties</code> and <code>setDOMProperties</code> methods. * * @ThreadSafe * @Version $Revision$ */ public class XMLParserActivator implements BundleActivator, ServiceFactory { /** Context of this bundle */ private volatile BundleContext context; /** * Filename containing the SAX Parser Factory Class name. Also used as the * basis for the <code>SERVICE_PID<code> registration property. */ public static final String SAXFACTORYNAME = "javax.xml.parsers.SAXParserFactory"; /** * Filename containing the DOM Parser Factory Class name. Also used as the * basis for the <code>SERVICE_PID</code> registration property. */ public static final String DOMFACTORYNAME = "javax.xml.parsers.DocumentBuilderFactory"; /** Path to the factory class name files */ private static final String PARSERCLASSFILEPATH = "/META-INF/services/"; /** Fully qualified path name of SAX Parser Factory Class Name file */ public static final String SAXCLASSFILE = PARSERCLASSFILEPATH + SAXFACTORYNAME; /** Fully qualified path name of DOM Parser Factory Class Name file */ public static final String DOMCLASSFILE = PARSERCLASSFILEPATH + DOMFACTORYNAME; /** SAX Factory Service Description */ private static final String SAXFACTORYDESCRIPTION = "A JAXP Compliant SAX Parser"; /** DOM Factory Service Description */ private static final String DOMFACTORYDESCRIPTION = "A JAXP Compliant DOM Parser"; /** * Service property specifying if factory is configured to support * validating parsers. The value is of type <code>Boolean</code>. */ public static final String PARSER_VALIDATING = "parser.validating"; /** * Service property specifying if factory is configured to support namespace * aware parsers. The value is of type <code>Boolean</code>. */ public static final String PARSER_NAMESPACEAWARE = "parser.namespaceAware"; /** * Key for parser factory name property - this must be saved in the parsers * properties hashtable so that the parser factory can be instantiated from * a ServiceReference */ private static final String FACTORYNAMEKEY = "parser.factoryname"; /** * Called when this bundle is started so the Framework can perform the * bundle-specific activities necessary to start this bundle. This method * can be used to register services or to allocate any resources that this * bundle needs. * * <p> * This method must complete and return to its caller in a timely manner. * * <p> * This method attempts to register a SAX and DOM parser with the * Framework's service registry. * * @param context The execution context of the bundle being started. * @throws java.lang.Exception If this method throws an exception, this * bundle is marked as stopped and the Framework will remove this * bundle's listeners, unregister all services registered by this * bundle, and release all services used by this bundle. */ public void start(BundleContext context) throws Exception { this.context = context; Bundle parserBundle = context.getBundle(); try { // check for sax parsers registerSAXParsers(getParserFactoryClassNames(parserBundle .getResource(SAXCLASSFILE))); // check for dom parsers registerDOMParsers(getParserFactoryClassNames(parserBundle .getResource(DOMCLASSFILE))); } catch (IOException ioe) { // if there were any IO errors accessing the resource files // containing the class names ioe.printStackTrace(); throw new FactoryConfigurationError(ioe); } } /** * This method has nothing to do as all active service registrations will * automatically get unregistered when the bundle stops. * * @param context The execution context of the bundle being stopped. * @throws java.lang.Exception If this method throws an exception, the * bundle is still marked as stopped, and the Framework will remove * the bundle's listeners, unregister all services registered by the * bundle, and release all services used by the bundle. */ public void stop(BundleContext context) throws Exception { // framework will automatically unregister the parser services } /** * Given the URL for a file, reads and returns the parser class names. There * may be multiple classes specified in this file, one per line. There may * also be comment lines in the file, which begin with "#". * * @param parserUrl The URL of the service file containing the parser class * names * @return A vector of strings containing the parser class names or null if * parserUrl is null * @throws IOException if there is a problem reading the URL input stream */ private Vector getParserFactoryClassNames(URL parserUrl) throws IOException { Vector v = new Vector(1); if (parserUrl != null) { String parserFactoryClassName = null; InputStream is = parserUrl.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); while (true) { parserFactoryClassName = br.readLine(); if (parserFactoryClassName == null) { break; // end of file reached } String pfcName = parserFactoryClassName.trim(); if (pfcName.length() == 0) { continue; // blank line } int commentIdx = pfcName.indexOf("#"); if (commentIdx == 0) { // comment line continue; } else if (commentIdx < 0) { // no comment on this line v.addElement(pfcName); } else { v.addElement(pfcName.substring(0, commentIdx).trim()); } } return v; } else { return null; } } /** * Register SAX Parser Factory Services with the framework. * * @param parserFactoryClassNames - a <code>Vector</code> of * <code>String</code> objects containing the names of the parser * Factory Classes * @throws FactoryConfigurationError if thrown from <code>getFactory</code> */ private void registerSAXParsers(Vector parserFactoryClassNames) throws FactoryConfigurationError { if (parserFactoryClassNames != null) { Enumeration e = parserFactoryClassNames.elements(); int index = 0; while (e.hasMoreElements()) { String parserFactoryClassName = (String) e.nextElement(); // create a sax parser factory just to get it's default // properties. It will never be used since // this class will operate as a service factory and give each // service requestor it's own SaxParserFactory SAXParserFactory factory = (SAXParserFactory) getFactory(parserFactoryClassName); Hashtable properties = new Hashtable(7); // figure out the default properties of the parser setDefaultSAXProperties(factory, properties, index); // store the parser factory class name in the properties so that // it can be retrieved when getService is called // to return a parser factory properties.put(FACTORYNAMEKEY, parserFactoryClassName); // release the factory factory = null; // register the factory as a service context.registerService(SAXFACTORYNAME, this, properties); index++; } } } /** * <p> * Set the SAX Parser Service Properties. By default, the following * properties are set: * <ul> * <li><code>SERVICE_DESCRIPTION</code> * <li><code>SERVICE_PID</code> * <li><code>PARSER_VALIDATING</code>- instantiates a parser and queries * it to find out whether it is validating or not * <li><code>PARSER_NAMESPACEAWARE</code>- instantiates a parser and * queries it to find out whether it is namespace aware or not * <ul> * * @param factory The <code>SAXParserFactory</code> object * @param props <code>Hashtable</code> of service properties. */ private void setDefaultSAXProperties(SAXParserFactory factory, Hashtable props, int index) { props.put(Constants.SERVICE_DESCRIPTION, SAXFACTORYDESCRIPTION); props.put(Constants.SERVICE_PID, SAXFACTORYNAME + "." + context.getBundle().getBundleId() + "." + index); setSAXProperties(factory, props); } /** * <p> * Set the customizable SAX Parser Service Properties. * * <p> * This method attempts to instantiate a validating parser and a namespace * aware parser to determine if the parser can support those features. The * appropriate properties are then set in the specified properties object. * * <p> * This method can be overridden to add additional SAX2 features and * properties. If you want to be able to filter searches of the OSGi service * registry, this method must put a key, value pair into the properties * object for each feature or property. For example, * * properties.put("http://www.acme.com/features/foo", Boolean.TRUE); * * @param factory - the SAXParserFactory object * @param properties - the properties object for the service */ public void setSAXProperties(SAXParserFactory factory, Hashtable properties) { // check if this parser can be configured to validate boolean validating = true; factory.setValidating(true); factory.setNamespaceAware(false); try { factory.newSAXParser(); } catch (Exception pce_val) { validating = false; } // check if this parser can be configured to be namespaceaware boolean namespaceaware = true; factory.setValidating(false); factory.setNamespaceAware(true); try { factory.newSAXParser(); } catch (Exception pce_nsa) { namespaceaware = false; } // set the factory values factory.setValidating(validating); factory.setNamespaceAware(namespaceaware); // set the OSGi service properties properties.put(PARSER_NAMESPACEAWARE, new Boolean(namespaceaware)); properties.put(PARSER_VALIDATING, new Boolean(validating)); } /** * Register DOM Parser Factory Services with the framework. * * @param parserFactoryClassNames - a <code>Vector</code> of * <code>String</code> objects containing the names of the parser * Factory Classes * @throws FactoryConfigurationError if thrown from <code>getFactory</code> */ private void registerDOMParsers(Vector parserFactoryClassNames) throws FactoryConfigurationError { if (parserFactoryClassNames != null) { Enumeration e = parserFactoryClassNames.elements(); int index = 0; while (e.hasMoreElements()) { String parserFactoryClassName = (String) e.nextElement(); // create a dom parser factory just to get it's default // properties. It will never be used since // this class will operate as a service factory and give each // service requestor it's own DocumentBuilderFactory DocumentBuilderFactory factory = (DocumentBuilderFactory) getFactory(parserFactoryClassName); Hashtable properties = new Hashtable(7); // figure out the default properties of the parser setDefaultDOMProperties(factory, properties, index); // store the parser factory class name in the properties so that // it can be retrieved when getService is called // to return a parser factory properties.put(FACTORYNAMEKEY, parserFactoryClassName); // release the factory factory = null; // register the factory as a service context.registerService(DOMFACTORYNAME, this, properties); index++; } } } /** * Set the DOM parser service properties. * * By default, the following properties are set: * <ul> * <li><code>SERVICE_DESCRIPTION</code> * <li><code>SERVICE_PID</code> * <li><code>PARSER_VALIDATING</code> * <li><code>PARSER_NAMESPACEAWARE</code> * <ul> * * @param factory The <code>DocumentBuilderFactory</code> object * @param props <code>Hashtable</code> of service properties. */ private void setDefaultDOMProperties(DocumentBuilderFactory factory, Hashtable props, int index) { props.put(Constants.SERVICE_DESCRIPTION, DOMFACTORYDESCRIPTION); props.put(Constants.SERVICE_PID, DOMFACTORYNAME + "." + context.getBundle().getBundleId() + "." + index); setDOMProperties(factory, props); } /** * <p> * Set the customizable DOM Parser Service Properties. * * <p> * This method attempts to instantiate a validating parser and a namespace * aware parser to determine if the parser can support those features. The * appropriate properties are then set in the specified props object. * * <p> * This method can be overridden to add additional DOM2 features and * properties. If you want to be able to filter searches of the OSGi service * registry, this method must put a key, value pair into the properties * object for each feature or property. For example, * * properties.put("http://www.acme.com/features/foo", Boolean.TRUE); * * @param factory - the DocumentBuilderFactory object * @param props - Hashtable of service properties. */ public void setDOMProperties(DocumentBuilderFactory factory, Hashtable props) { // check if this parser can be configured to validate boolean validating = true; factory.setValidating(true); factory.setNamespaceAware(false); try { factory.newDocumentBuilder(); } catch (Exception pce_val) { validating = false; } // check if this parser can be configured to be namespaceaware boolean namespaceaware = true; factory.setValidating(false); factory.setNamespaceAware(true); try { factory.newDocumentBuilder(); } catch (Exception pce_nsa) { namespaceaware = false; } // set the factory values factory.setValidating(validating); factory.setNamespaceAware(namespaceaware); // set the OSGi service properties props.put(PARSER_VALIDATING, new Boolean(validating)); props.put(PARSER_NAMESPACEAWARE, new Boolean(namespaceaware)); } /** * Given a parser factory class name, instantiate that class. * * @param parserFactoryClassName A <code>String</code> object containing * the name of the parser factory class * @return a parserFactoryClass Object * @pre parserFactoryClassName!=null */ private Object getFactory(String parserFactoryClassName) throws FactoryConfigurationError { Exception e = null; try { return context.getBundle().loadClass(parserFactoryClassName) .newInstance(); } catch (ClassNotFoundException cnfe) { e = cnfe; } catch (InstantiationException ie) { e = ie; } catch (IllegalAccessException iae) { e = iae; } throw new FactoryConfigurationError(e); } /** * Creates a new XML Parser Factory object. * * <p> * A unique XML Parser Factory object is returned for each call to this * method. * * <p> * The returned XML Parser Factory object will be configured for validating * and namespace aware support as specified in the service properties of the * specified ServiceRegistration object. * * This method can be overridden to configure additional features in the * returned XML Parser Factory object. * * @param bundle The bundle using the service. * @param registration The <code>ServiceRegistration</code> object for the * service. * @return A new, configured XML Parser Factory object or null if a * configuration error was encountered */ public Object getService(Bundle bundle, ServiceRegistration registration) { ServiceReference sref = registration.getReference(); String parserFactoryClassName = (String) sref .getProperty(FACTORYNAMEKEY); try { // need to set factory properties Object factory = getFactory(parserFactoryClassName); if (factory instanceof SAXParserFactory) { ((SAXParserFactory) factory).setValidating(((Boolean) sref .getProperty(PARSER_VALIDATING)).booleanValue()); ((SAXParserFactory) factory).setNamespaceAware(((Boolean) sref .getProperty(PARSER_NAMESPACEAWARE)).booleanValue()); } else if (factory instanceof DocumentBuilderFactory) { ((DocumentBuilderFactory) factory) .setValidating(((Boolean) sref .getProperty(PARSER_VALIDATING)) .booleanValue()); ((DocumentBuilderFactory) factory) .setNamespaceAware(((Boolean) sref .getProperty(PARSER_NAMESPACEAWARE)) .booleanValue()); } return factory; } catch (FactoryConfigurationError fce) { fce.printStackTrace(); return null; } } /** * Releases a XML Parser Factory object. * * @param bundle The bundle releasing the service. * @param registration The <code>ServiceRegistration</code> object for the * service. * @param service The XML Parser Factory object returned by a previous call * to the <code>getService</code> method. */ public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) { } }
@Version tag must be @version :-)
org.osgi.util.xml/src/org/osgi/util/xml/XMLParserActivator.java
@Version tag must be @version :-)
<ide><path>rg.osgi.util.xml/src/org/osgi/util/xml/XMLParserActivator.java <ide> <ide> package org.osgi.util.xml; <ide> <del>import java.io.*; <add>import java.io.BufferedReader; <add>import java.io.IOException; <add>import java.io.InputStream; <add>import java.io.InputStreamReader; <ide> import java.net.URL; <del>import java.util.*; <del> <del>import javax.xml.parsers.*; <del> <del>import org.osgi.framework.*; <add>import java.util.Enumeration; <add>import java.util.Hashtable; <add>import java.util.Vector; <add> <add>import javax.xml.parsers.DocumentBuilderFactory; <add>import javax.xml.parsers.FactoryConfigurationError; <add>import javax.xml.parsers.SAXParserFactory; <add> <add>import org.osgi.framework.Bundle; <add>import org.osgi.framework.BundleActivator; <add>import org.osgi.framework.BundleContext; <add>import org.osgi.framework.Constants; <add>import org.osgi.framework.ServiceFactory; <add>import org.osgi.framework.ServiceReference; <add>import org.osgi.framework.ServiceRegistration; <ide> <ide> /** <ide> * A BundleActivator class that allows any JAXP compliant XML Parser to register <ide> * An XMLParserActivator assumes that it can find the class file names of the <ide> * factory classes in the following files: <ide> * <ul> <del> * <li><code>/META-INF/services/javax.xml.parsers.SAXParserFactory</code> is <del> * a file contained in a jar available to the runtime which contains the <add> * <li><code>/META-INF/services/javax.xml.parsers.SAXParserFactory</code> is a <add> * file contained in a jar available to the runtime which contains the <ide> * implementation class name(s) of the SAXParserFactory. <ide> * <li><code>/META-INF/services/javax.xml.parsers.DocumentBuilderFactory</code> <ide> * is a file contained in a jar available to the runtime which contains the <ide> * <ide> * <p> <ide> * <code>XMLParserActivator</code> attempts to instantiate both the <del> * <code>SAXParserFactory</code> and the <code>DocumentBuilderFactory</code>. <del> * It registers each factory with the framework along with service properties: <add> * <code>SAXParserFactory</code> and the <code>DocumentBuilderFactory</code>. It <add> * registers each factory with the framework along with service properties: <ide> * <ul> <del> * <li>{@link #PARSER_VALIDATING}- indicates if this factory supports <del> * validating parsers. It's value is a <code>Boolean</code>. <add> * <li>{@link #PARSER_VALIDATING}- indicates if this factory supports validating <add> * parsers. It's value is a <code>Boolean</code>. <ide> * <li>{@link #PARSER_NAMESPACEAWARE}- indicates if this factory supports <ide> * namespace aware parsers It's value is a <code>Boolean</code>. <ide> * </ul> <ide> * <code>setSAXProperties</code> and <code>setDOMProperties</code> methods. <ide> * <ide> * @ThreadSafe <del> * @Version $Revision$ <add> * @version $Revision$ <ide> */ <ide> public class XMLParserActivator implements BundleActivator, ServiceFactory { <ide> /** Context of this bundle */
Java
mit
d4a7c90b0de948dcffa0d408405206999a4f123b
0
douggie/XChange
/* * The MIT License * * Copyright 2015-2016 Coinmate. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.knowm.xchange.coinmate; import org.knowm.xchange.currency.CurrencyPair; /** * Conversion between XChange CurrencyPair and Coinmate API * * @author Martin Stachon */ public class CoinmateUtils { public static String getPair(CurrencyPair currencyPair) { if (currencyPair == null) { return null; } return currencyPair.base.getCurrencyCode().toUpperCase() + "_" + currencyPair.counter.getCurrencyCode().toUpperCase(); } public static CurrencyPair getPair(String currencyPair) { return new CurrencyPair(currencyPair.replace("_","/")); } }
xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/CoinmateUtils.java
/* * The MIT License * * Copyright 2015-2016 Coinmate. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.knowm.xchange.coinmate; import org.knowm.xchange.currency.CurrencyPair; /** * Conversion between XChange CurrencyPair and Coinmate API * * @author Martin Stachon */ public class CoinmateUtils { public static String getPair(CurrencyPair currencyPair) { // if (currencyPair == null) { // return null; // } return currencyPair.base.getCurrencyCode().toUpperCase() + "_" + currencyPair.counter.getCurrencyCode().toUpperCase(); } public static CurrencyPair getPair(String currencyPair) { return new CurrencyPair(currencyPair.replace("_","/")); } }
including null option on CoinmateUtils.getPairs
xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/CoinmateUtils.java
including null option on CoinmateUtils.getPairs
<ide><path>change-coinmate/src/main/java/org/knowm/xchange/coinmate/CoinmateUtils.java <ide> public class CoinmateUtils { <ide> <ide> public static String getPair(CurrencyPair currencyPair) { <del>// if (currencyPair == null) { <del>// return null; <del>// } <add> if (currencyPair == null) { <add> return null; <add> } <ide> return currencyPair.base.getCurrencyCode().toUpperCase() <ide> + "_" <ide> + currencyPair.counter.getCurrencyCode().toUpperCase();
Java
mit
c41a67a7ca5c1938e6d2dfe4466fbb2f08063718
0
CMPUT301F17T08/habit_rabbit
package ca.ualberta.cmput301f17t08.habitrabbit; import java.util.ArrayList; /** * Created by mseneshen on 2017-10-23. */ public class User { private String username; private ArrayList<Habit> habitList; private ArrayList<User> followerList; private ArrayList<User> followingList; private ArrayList<User> followRequests; private ArrayList<Habit> historylist; public User(String username){ this.username = username; this.habitList = new ArrayList<Habit>(); this.followerList = new ArrayList<User>(); this.followingList = new ArrayList<User>(); this.followRequests = new ArrayList<User>(); this.historylist = new ArrayList<Habit>(); } public void addFollower(User follower) { return; } public void removeFollower(User follower) { return; } public void addHabit(Habit habit) { return; } public void removeHabit(Habit habit) { return; } public ArrayList<Habit> filterHistory(String keyword, String filterType){return null;} public ArrayList<Habit> habitmissed(Habit habit){return null;} public ArrayList<User> getFollowers() { return null; } public ArrayList<Habit> getHabits() { return null; } }
app/src/main/java/ca/ualberta/cmput301f17t08/habitrabbit/User.java
package ca.ualberta.cmput301f17t08.habitrabbit; import java.util.ArrayList; /** * Created by mseneshen on 2017-10-23. */ public class User { private String username; private ArrayList<Habit> habitList; private ArrayList<User> followerList; private ArrayList<User> followingList; private ArrayList<User> followRequests; private ArrayList<Habit> historylist; public ArrayList<User> getFollowers() { return null; } public void addFollower(User follower) { return; } public void removeFollower(User follower) { return; } public ArrayList<Habit> getHabits() { return null; } public void addHabit(Habit habit) { return; } public void removeHabit(Habit habit) { return; } }
working on user class
app/src/main/java/ca/ualberta/cmput301f17t08/habitrabbit/User.java
working on user class
<ide><path>pp/src/main/java/ca/ualberta/cmput301f17t08/habitrabbit/User.java <ide> private ArrayList<User> followRequests; <ide> private ArrayList<Habit> historylist; <ide> <add> public User(String username){ <add> this.username = username; <add> this.habitList = new ArrayList<Habit>(); <add> this.followerList = new ArrayList<User>(); <add> this.followingList = new ArrayList<User>(); <add> this.followRequests = new ArrayList<User>(); <add> this.historylist = new ArrayList<Habit>(); <add> <add> } <add> <add> public void addFollower(User follower) { return; } <add> public void removeFollower(User follower) { return; } <add> public void addHabit(Habit habit) { return; } <add> public void removeHabit(Habit habit) { return; } <add> public ArrayList<Habit> filterHistory(String keyword, String filterType){return null;} <add> public ArrayList<Habit> habitmissed(Habit habit){return null;} <add> <add> <ide> <ide> <ide> public ArrayList<User> getFollowers() { return null; } <del> public void addFollower(User follower) { return; } <del> public void removeFollower(User follower) { return; } <ide> <ide> public ArrayList<Habit> getHabits() { return null; } <del> public void addHabit(Habit habit) { return; } <del> public void removeHabit(Habit habit) { return; } <ide> <ide> }
JavaScript
agpl-3.0
b16857db9065e6e9121830c108b5e8b17fd0b12f
0
kaltura/mwEmbed,omridevk/mwEmbed,FlixMaster/mwEmbed,FlixMaster/mwEmbed,FlixMaster/mwEmbed,FlixMaster/mwEmbed,kaltura/mwEmbed,omridevk/mwEmbed,kaltura/mwEmbed,kaltura/mwEmbed,omridevk/mwEmbed,omridevk/mwEmbed
/** * KWidget library provided embed layer services to html5 and flash players, as well as client side abstraction for some kaltura services. */ (function ($) { // Use strict ECMAScript 5 "use strict"; // Don't re-initialize kWidget if (window.kWidget) { return; } var kWidget = { //store the start time of the kwidget init startTime: {}, //store the load time of the player loadTime: {}, // Stores widgets that are ready: readyWidgets: {}, // stores original embed settings per widget: widgetOriginalSettings: {}, // First ready callback issued readyCallbacks: [], // List of widgets that have been destroyed destroyedWidgets: {}, // List per Widget callback, for clean destroy perWidgetCallback: {}, // Store the widget id ready callbacks in an array to avoid stacking on same id rewrite readyCallbackPerWidget: {}, listenerList: {}, // Stores per uiConf user agent rewrite rules userAgentPlayerRules: {}, // flag for the already added css rule: alreadyAddedThumbRules: false, // For storing iframe payloads via server side include, instead of an additional request // stored per player id iframeAutoEmbedCache: {}, // For storing iframe urls // Stored per player id iframeUrls: {}, /** * The master kWidget setup function setups up bindings for rewrites and * proxy of jsCallbackReady * * MUST BE CALLED AFTER all of the mwEmbedLoader.php includes. */ setup: function () { var _this = this; /** * set version: */ mw.setConfig('version', MWEMBED_VERSION); /** * Check the kWidget for environment settings and set appropriate flags */ this.checkEnvironment(); /** * Override flash methods, like swfObject, flashembed etc. * * NOTE for this override to work it your flash embed library must be included before mwEmbed */ this.overrideFlashEmbedMethods(); /** * Method call to proxy the jsCallbackReady * * We try to proxy both at include time and at domReady time */ this.proxyJsCallbackready(); this.domReady(function () { // set dom ready flag _this.domIsReady = true; _this.proxyJsCallbackready(); }); /** * Call the object tag rewrite, which will rewrite on-page object tags */ this.domReady(function () { _this.rewriteObjectTags(); }); }, /** * Checks the onPage environment context and sets appropriate flags. */ checkEnvironment: function () { // Note forceMobileHTML5 url flag be disabled by uiConf on the iframe side of the player // with: if ( document.URL.indexOf( 'forceMobileHTML5' ) !== -1 && !mw.getConfig( 'disableForceMobileHTML5' ) ) { mw.setConfig( 'forceMobileHTML5' , true ); } // Check for debugKalturaPlayer in url and set debug mode to true if ( document.URL.indexOf( 'debugKalturaPlayer' ) !== -1 ) { mw.setConfig( 'debug' , true ); } // Check for forceKPlayer in the URL if ( document.URL.indexOf( 'forceKPlayer' ) !== -1 ) { mw.setConfig( 'EmbedPlayer.ForceKPlayer' , true ); } var ua = navigator.userAgent; // Check if browser should use flash ( IE < 9 ) var ieMatch = document.documentMode ? ['', document.documentMode] : ua.match(/MSIE\s([0-9]+)/); if ( (ieMatch && parseInt( ieMatch[1] ) < 9) || document.URL.indexOf( 'forceFlash' ) !== -1 ) { mw.setConfig( 'Kaltura.ForceFlashOnDesktop' , true ); } // Blackberry does not really support html5 if ( ua.indexOf( 'BlackBerry' ) != -1 ) { mw.setConfig( 'EmbedPlayer.DisableVideoTagSupport' , true ); mw.setConfig( 'EmbedPlayer.NotPlayableDownloadLink' , true ); } if ( ua.indexOf( 'kalturaNativeCordovaPlayer' ) != -1 ) { mw.setConfig( 'EmbedPlayer.ForceNativeComponent' , true ); if ( !mw.getConfig( 'EmbedPlayer.IsIframeServer' ) ) { var cordovaPath; var cordovaKWidgetPath; if ( this.isAndroid() ) { cordovaPath = "/modules/EmbedPlayer/binPlayers/cordova/android/cordova.js"; } else { cordovaPath = "/modules/EmbedPlayer/binPlayers/cordova/ios/cordova.js"; } cordovaKWidgetPath = "/kWidget/cordova.kWidget.js"; document.write( '<script src="' + this.getPath() + cordovaPath + '"></scr' + 'ipt>' ); document.write( '<script src="' + this.getPath() + cordovaKWidgetPath + '"></scr' + 'ipt>' ); } } // iOS less than 5 does not play well with HLS: if ( /(iPhone|iPod|iPad)/i.test( ua ) ) { if ( /OS [2-4]_\d(_\d)? like Mac OS X/i.test( ua ) || (/CPU like Mac OS X/i.test( ua ) ) ) { mw.setConfig( 'Kaltura.UseAppleAdaptive' , false ); } } // Set iframe config if in the client page, will be passed to the iframe along with other config if ( !mw.getConfig( 'EmbedPlayer.IsIframeServer' ) ) { mw.setConfig( 'EmbedPlayer.IframeParentUrl' , document.URL ); mw.setConfig( 'EmbedPlayer.IframeParentTitle' , document.title ); mw.setConfig( 'EmbedPlayer.IframeParentReferrer' , document.referrer ); // Fix for iOS 5 not rendering iframe correctly when moving back/forward // http://stackoverflow.com/questions/7988967/problems-with-page-cache-in-ios-5-safari-when-navigating-back-unload-event-not if ( /(iPhone|iPod|iPad)/i.test( navigator.userAgent ) ) { if ( /OS [1-5](.*) like Mac OS X/i.test( navigator.userAgent ) ) { window.onpageshow = function ( evt ) { // If persisted then it is in the page cache, force a reload of the page. if ( evt.persisted ) { document.body.style.display = "none"; location.reload(); } }; } } } //Show non-production error by default, and allow overriding via flashvar if (!mw.getConfig( "Kaltura.SupressNonProductionUrlsWarning", false )) { // Check if using staging server on non-staging site: if ( // make sure this is Kaltura SaaS we are checking: mw.getConfig("Kaltura.ServiceUrl").indexOf('kaltura.com') != -1 && // check that the library is not on production this.getPath().indexOf('i.kaltura.com') == -1 && this.getPath().indexOf('isec.kaltura.com') == -1 && // check that we player is not on a staging site: window.location.host != 'kgit.html5video.org' && window.location.host != 'player.kaltura.com' && window.location.host != 'localhost' ) { if (console && console.error) { console.error("Error: Using non-production version of kaltura player library. Please see http://knowledge.kaltura.com/production-player-urls") } } } if (mw.getConfig( 'EmbedPlayer.ForceNativeComponent')) { // set up window.kNativeSdk window.kNativeSdk = window.kNativeSdk || {}; var typeMap = function(names) { if (typeof names !== 'string') { return []; } names = names.split(","); var mimeTypes = []; var map = { "dash": "application/dash+xml", "mp4": "video/mp4", "wvm": "video/wvm", "hls": "application/vnd.apple.mpegurl" }; for (var i = 0; i < names.length; i++) { mimeTypes.push(map[names[i]]); } return mimeTypes; }; // The Native SDK provides two lists of supported formats, after the hash sign. // Example: #nativeSdkDrmFormats=dash,wvm&nativeSdkAllFormats=dash,mp4,hls,wvm var drmFormats = kWidget.getHashParam("nativeSdkDrmFormats") || "wvm"; var allFormats = kWidget.getHashParam("nativeSdkAllFormats") || "wvm,mp4,hls"; window.kNativeSdk.drmFormats = typeMap(drmFormats); window.kNativeSdk.allFormats = typeMap(allFormats); } }, /** * Checks for the existence of jsReadyCallback and stores it locally. * all ready calls then are wrapped by the kWidget jsCallBackready function. */ proxiedJsCallback: null, waitForLibraryChecks: true, jsReadyCalledForIds: [], proxyJsCallbackready: function () { var _this = this; var jsCallbackProxy = function (widgetId) { // check if we need to wait. if (_this.waitForLibraryChecks) { // wait for library checks _this.jsReadyCalledForIds.push(widgetId); return; } // else we can call the jsReadyCallback directly: _this.jsCallbackReady(widgetId); }; // Always proxy js callback if (!this.proxiedJsCallback) { // Setup a proxied ready function: this.proxiedJsCallback = window['jsCallbackReady'] || true; // Override the actual jsCallbackReady window['jsCallbackReady'] = jsCallbackProxy } // secondary domready call check that jsCallbackReady was not overwritten: if (window['jsCallbackReady'].toString() != jsCallbackProxy.toString()) { this.proxiedJsCallback = window['jsCallbackReady']; // Override the actual jsCallbackReady with proxy window['jsCallbackReady'] = jsCallbackProxy } }, /** * The kWidget proxied jsCallbackReady * @param {string} widgetId The id of the widget that is ready */ jsCallbackReady: function (widgetId) { var _this = this; _this.log("jsCallbackReady for " + widgetId); if (this.destroyedWidgets[ widgetId ]) { // don't issue ready callbacks on destroyed widgets: return; } var player = document.getElementById(widgetId); if (!player || !player.evaluate) { this.callJsCallback(); this.log("Error:: jsCallbackReady called on invalid player Id:" + widgetId); return; } // extend the element with kBind kUnbind: this.extendJsListener(player); // check for inlineSciprts mode original settings: if( this.widgetOriginalSettings[widgetId] ){ // TODO these settings may be a bit late for plugins config ( should be set earlier in build out ) // for now just null out settings and changeMedia: player.kBind( 'kdpEmpty', function(){ player.sendNotification('changeMedia', {'entryId': _this.widgetOriginalSettings[widgetId].entry_id} ); } ); //player.sendNotification('changeMedia', {'entryId': this.widgetOriginalSettings[widgetId].entry_id} ); } var kdpVersion = player.evaluate('{playerStatusProxy.kdpVersion}'); //set the load time attribute supported in version kdp 3.7.x if (mw.versionIsAtLeast('v3.7.0', kdpVersion)) { _this.log("Error: Unsuported KDP version"); } else{ player.kBind('mediaReady', function () { // Set the load time against startTime for the current playerId: player.setKDPAttribute("playerStatusProxy", "loadTime", ( (new Date().getTime() - _this.startTime[ widgetId ] ) / 1000.0 ).toFixed(2) ); }); } // Support closing menu inside the player if (!mw.getConfig('EmbedPlayer.IsIframeServer')) { document.onclick = function () { //If player is destroyed don't send notification if (!_this.destroyedWidgets[ player.id ]) { player.sendNotification( 'onFocusOutOfIframe' ); } }; } // Check for proxied jsReadyCallback: if (typeof this.proxiedJsCallback == 'function') { this.proxiedJsCallback(widgetId); } this.callJsCallback(widgetId); }, callJsCallback: function (widgetId) { // Issue the callback for all readyCallbacks for (var i = 0; i < this.readyCallbacks.length; i++) { this.readyCallbacks[i](widgetId); } if (widgetId) { this.readyWidgets[ widgetId ] = true; } }, /** * Function to flag player mode checks. */ playerModeChecksDone: function () { // no need to wait for library checks any longer: this.waitForLibraryChecks = false; // Call any callbacks in the queue: for (var i = 0; i < this.jsReadyCalledForIds.length; i++) { var widgetId = this.jsReadyCalledForIds[i]; this.jsCallbackReady(widgetId); } // empty out the ready callback queue this.jsReadyCalledForIds = []; }, isDownloadLinkPlayer: function () { if (window.location.href.indexOf('forceDownloadPlayer') > -1 || mw.getConfig("EmbedPlayer.NotPlayableDownloadLink")) { return true; } return false; }, /** * The base embed method * @param targetId {String} Optional targetID string ( if not included, you must include in json) * @param settings {Object} Object of settings to be used in embedding. */ embed: function (targetId, settings) { if (this.isDownloadLinkPlayer()) { return this.thumbEmbed(targetId, settings, true); } var _this = this; // Supports passing settings object as the first parameter if (typeof targetId === 'object') { settings = targetId; if (!settings.targetId) { this.log('Error: Missing target element Id'); } targetId = settings.targetId; } // set player load check at start embed method call this.startTime[targetId] = new Date().getTime(); // Check if we have flashvars object if (!settings.flashvars) { settings.flashvars = {}; } if (this.isMobileDevice()){ if (settings.flashvars['layout']){ settings.flashvars.layout['skin'] = "kdark"; } } if ( document.URL.indexOf('forceKalturaNativeComponentPlayer') !== -1 || document.URL.indexOf('forceKalturaNative') !== -1) { settings.flashvars["nativeCallout"] = { plugin: true } } /** * Embed settings checks */ if (!settings.wid) { this.log("Error: kWidget.embed missing wid"); return; } var uiconf_id = settings.uiconf_id; var confFile = settings.flashvars.confFilePath ? settings.flashvars.confFilePath : settings.flashvars.jsonConfig; if (!uiconf_id && !confFile) { this.log("Error: kWidget.embed missing uiconf_id or confFile"); return; } // Make sure the replace target exists: var elm = document.getElementById(targetId); if (!elm) { this.log("Error: kWidget.embed could not find target: " + targetId); return false; // No target found ( probably already done ) } // Don't rewrite special key kaltura_player_iframe_no_rewrite if (elm.getAttribute('name') == 'kaltura_player_iframe_no_rewrite') { return; } // Check for "auto" localization and inject browser language. // We can't inject server side, because, we don't want to mangle the cached response // with params that are not in the request URL ( i.e AcceptLanguage headers ) if (settings.flashvars['localizationCode'] == 'auto') { var browserLangCode = window.navigator.userLanguage || window.navigator.language; // Just take the first part of the code ( not the country code ) settings.flashvars['localizationCode'] = browserLangCode.split('-')[0]; } // Empty the target ( don't keep SEO links on Page while loading iframe ) try { elm.innerHTML = ''; } catch (e) { // IE8 can't handle innerHTML on "read only" targets . } // Check for size override in kWidget embed call function checkSizeOverride(dim) { if (settings[ dim ]) { // check for non px value: if (parseInt(settings[ dim ]) == settings[ dim ]) { settings[ dim ] += 'px'; } elm.style[ dim ] = settings[ dim ]; } } checkSizeOverride('width'); checkSizeOverride('height'); // Unset any destroyed widget with the same id: if (this.destroyedWidgets[ targetId ]) { delete( this.destroyedWidgets[ targetId ] ); } // Check for ForceIframeEmbed flag if (mw.getConfig('Kaltura.ForceIframeEmbed') === true) { this.outputIframeWithoutApi(targetId, settings); return; } if (settings.readyCallback) { // only add a callback if we don't already have one for this id: var adCallback = !this.perWidgetCallback[ targetId ]; // add the per widget callback: this.perWidgetCallback[ targetId ] = settings.readyCallback; // Only add the ready callback for the current targetId being rewritten. if (adCallback) { this.addReadyCallback(function (videoId) { if (videoId == targetId && _this.perWidgetCallback[ videoId ]) { _this.perWidgetCallback[ videoId ](videoId); } }); } } // Be sure to jsCallbackready is proxied in dynamic embed call situations: this.proxyJsCallbackready(); settings.isHTML5 = this.isUiConfIdHTML5(uiconf_id); /** * Local scope doEmbed action, either writes out a msg, flash player */ var doEmbedAction = function () { // Evaluate per user agent rules for actions if (uiconf_id && _this.userAgentPlayerRules && _this.userAgentPlayerRules[ uiconf_id ]) { var playerAction = _this.checkUserAgentPlayerRules(_this.userAgentPlayerRules[ uiconf_id ]); // Default play mode, if here and really using flash re-map: switch (playerAction.mode) { case 'flash': if (elm.nodeName.toLowerCase() == 'object') { // do do anything if we are already trying to rewrite an object tag return; } break; case 'leadWithHTML5': settings.isHTML5 = _this.isUiConfIdHTML5(uiconf_id); break; case 'forceMsg': var msg = playerAction.val; // write out a message: if (elm && elm.parentNode) { var divTarget = document.createElement("div"); divTarget.style.backgroundColor = "#000000"; divTarget.style.color = "#a4a4a4"; divTarget.style.width = elm.style.width; divTarget.style.height = elm.style.height; divTarget.style.display = "table-cell"; divTarget.style.verticalAlign = "middle"; divTarget.style.textAlign = "center"; divTarget.style.fontSize = "1.5em"; divTarget.style.fontFamily = "Arial"; divTarget.style.fontWeight = "normal"; divTarget.innerHTML = unescape(msg); elm.parentNode.replaceChild(divTarget, elm); } return; break; } } // Check if we are dealing with an html5 native or flash player if (mw.getConfig("EmbedPlayer.ForceNativeComponent")) { _this.outputCordovaPlayer(targetId, settings); } else if (settings.isHTML5) { _this.outputHTML5Iframe(targetId, settings); } else { _this.outputFlashObject(targetId, settings); } } // load any onPage scripts if needed: // create a player list for missing uiconf check: var playerList = [ {'kEmbedSettings': settings } ]; // Load uiConfJS then call embed action this.loadUiConfJs(playerList, function () { // check that the proxy of js callback ready is up-to-date _this.proxyJsCallbackready(); doEmbedAction(); }); }, outputCordovaPlayer: function (targetId, settings) { var _this = this; if (cordova && cordova.kWidget) { cordova.kWidget.embed(targetId, settings); } else {//if cordova is not loaded run this function again after 500 ms setTimeout(function () { _this.outputCordovaPlayer(targetId, settings); }, 500) } }, addThumbCssRules: function () { if (this.alreadyAddedThumbRules) { return; } this.alreadyAddedThumbRules = true; var style = document.createElement('STYLE'); style.type = 'text/css'; var imagePath = this.getPath() + '/modules/MwEmbedSupport/skins/common/images/'; var cssText = '.kWidgetCentered {' + 'max-height: 100%; ' + 'max-width: 100%; ' + 'position: absolute; ' + 'top: 0; left: 0; right: 0; bottom: 0; ' + 'margin: auto; ' + '} ' + "\n" + '.kWidgetPlayBtn { ' + 'cursor:pointer;' + 'height: 53px;' + 'width: 70px;' + 'border-style: none;' + 'top: 50%; left: 50%; margin-top: -26.5px; margin-left: -35px; ' + 'background: url(\'' + imagePath + 'player_big_play_button.png\') ;' + 'z-index: 1;' + '} ' + "\n" + '.kWidgetAccessibilityLabel { ' + 'font-size:0;' + 'height: 1px;' + 'overflow: hidden;' + 'display:block;' + 'position:absolute;' + '} ' + "\n" + '.kWidgetPlayBtn:hover{ ' + 'background: url(\'' + imagePath + 'player_big_play_button_hover.png\');"' + '} '; if (this.isIE()) { style.styleSheet.cssText = cssText; } else { style.innerHTML = cssText; } // Append the style document.getElementsByTagName('HEAD')[0].appendChild(style); }, /** get the computed size of a target element */ getComputedSize: function (elm, dim) { var a = navigator.userAgent; if ((a.indexOf("msie") != -1) && (a.indexOf("opera") == -1 )) { return document.getElementById(theElt)[ 'offset' + dim[0].toUpperCase() + dim.substr(1) ]; } else { return parseInt(document.defaultView.getComputedStyle(elm, "").getPropertyValue(dim)); } }, /** * Used to do a light weight thumb embed player * the widget loaded anlytics event is triggered, * and a thumbReady callback is called * * All the other kWidget settings are invoked during playback. */ thumbEmbed: function (targetId, settings, forceDownload) { if (this.isDownloadLinkPlayer()) { forceDownload = true; } var _this = this; // Normalize the arguments if (typeof targetId === 'object') { settings = targetId; if (!settings.targetId) { this.log('Error: Missing target element Id'); } targetId = settings.targetId; } else { settings.targetId = targetId; } // Check if we have flashvars object if (!settings.flashvars) { settings.flashvars = {}; } // autoPlay media after thumbnail interaction settings.flashvars.autoPlay = true; // inject the centered css rule ( if not already ) this.addThumbCssRules(); // Add the width of the target to the settings: var elm = document.getElementById(targetId); if (!elm) { this.log("Error could not find target id, for thumbEmbed"); } elm.innerHTML = '' + '<div style="position: relative; width: 100%; height: 100%;">' + '<button aria-label="Play video content" class="kWidgetCentered kWidgetPlayBtn" ' + 'id="' + targetId + '_playBtn" ></button>' + '<img class="kWidgetCentered" src="' + this.getKalturaThumbUrl(settings) + '" alt="Video thumbnail">' + '</div>'; // Add a click binding to do the really embed: var playBtn = document.getElementById(targetId + '_playBtn'); this.addEvent(playBtn, 'click', function () { // Check for the ready callback: if (settings.readyCallback) { var orgEmbedCallback = settings.readyCallback; } settings.readyCallback = function (playerId) { // issue a play ( since we already clicked the play button ) var kdp = document.getElementById(playerId); kdp.kBind('mediaReady', function () { setTimeout(function () { if (_this.isMobileDevice()) { kdp.sendNotification('doPlay'); } }, 0); }); if (typeof orgEmbedCallback == 'function') { orgEmbedCallback(playerId); } } // Set a flag to capture the click event settings.captureClickEventForiOS = true; if (forceDownload) { window.open(_this.getDownloadLink(settings)); } else { // update the settings object kWidget.embed(settings); } }); // TOOD maybe a basic basic api ( doPlay support ? ) // thumb embed are ready as soon as they are embed: if (settings.thumbReadyCallback) { settings.thumbReadyCallback(targetId); } }, /** * Destroy a kWidget embed instance * * removes the target from the dom * * removes any associated * @param {Element|String} The target element or string to destroy */ destroy: function (target) { if (typeof target == 'string') { target = document.getElementById(target); } if (!target) { this.log("Error destory called without valid target"); return; } var targetId = target.id; var targetCss = target.style.cssText; var targetClass = target.className; var destoryId = target.getAttribute('id'); for (var id in this.readyWidgets) { if (id == destoryId) { delete( this.readyWidgets[ id ] ); } } this.destroyedWidgets[ destoryId ] = true; var newNode = document.createElement("div"); newNode.style.cssText = targetCss; newNode.id = targetId; newNode.className = targetClass; // remove the embed objects: target.parentNode.replaceChild(newNode, target); }, /** * Embeds the player from a set of on page objects with kEmbedSettings properties * @param {object} rewriteObjects set of in page object tags to be rewritten */ embedFromObjects: function (rewriteObjects) { for (var i = 0; i < rewriteObjects.length; i++) { var settings = rewriteObjects[i].kEmbedSettings; settings.width = rewriteObjects[i].width; settings.height = rewriteObjects[i].height; this.embed(rewriteObjects[i].id, rewriteObjects[i].kEmbedSettings); } }, /** * Extends the kWidget objects with (un)binding mechanism - kBind / kUnbind */ extendJsListener: function (player) { var _this = this; player.kBind = function (eventName, callback) { // Stores the index of anonymous callbacks for generating global functions var callbackIndex = 0; var globalCBName = ''; var _scope = this; // We can pass [eventName.namespace] as event name, we need it in order to remove listeners with their namespace if (typeof eventName == 'string') { var eventData = eventName.split('.', 2); var eventNamespace = ( eventData[1] ) ? eventData[1] : 'kWidget'; eventName = eventData[0]; } if (typeof callback == 'string') { globalCBName = callback; } else if (typeof callback == 'function') { // Make life easier for internal usage of the listener mapping by supporting // passing a callback by function ref var generateGlobalCBName = function () { globalCBName = 'kWidget_' + eventName + '_cb' + callbackIndex; if (window[ globalCBName ]) { callbackIndex++; generateGlobalCBName(); } }; generateGlobalCBName(); window[ globalCBName ] = function () { var args = Array.prototype.slice.call(arguments, 0); // move kbind into a timeout to restore javascript backtrace for errors, // instead of having flash directly call the callback breaking backtrace if (mw.getConfig('debug')) { setTimeout(function () { callback.apply(_scope, args); }, 0); } else { // note for production we directly issue the callback // this enables support for sync gesture rules for enterfullscreen. callback.apply(_scope, args); } }; } else { kWidget.log("Error: kWidget : bad callback type: " + callback); return; } // Storing a list of namespaces. Each namespace contains a list of eventnames and respective callbacks if (!_this.listenerList[ eventNamespace ]) { _this.listenerList[ eventNamespace ] = {} } if (!_this.listenerList[ eventNamespace ][ eventName ]) { _this.listenerList[ eventNamespace ][ eventName ] = globalCBName; } //kWidget.log( "kWidget :: kBind :: ( " + eventName + ", " + globalCBName + " )" ); player.addJsListener(eventName, globalCBName); return player; } player.kUnbind = function (eventName, callbackName) { //kWidget.log( "kWidget :: kUnbind :: ( " + eventName + ", " + callbackName + " )" ); if (typeof eventName == 'string') { var eventData = eventName.split('.', 2); var eventNamespace = eventData[1]; eventName = eventData[0]; // Remove event by namespace if (eventNamespace) { for (var listenerItem in _this.listenerList[ eventNamespace ]) { // Unbind the entire namespace if (!eventName) { player.removeJsListener(listenerItem, _this.listenerList[ eventNamespace ][ listenerItem ]); } // Only unbind the specified event within the namespace else { if (listenerItem == eventName) { player.removeJsListener(listenerItem, _this.listenerList[ eventNamespace ][ listenerItem ]); delete _this.listenerList[ eventNamespace ][ listenerItem ]; } } } _this.listenerList[ eventNamespace ] = null; } // No namespace was given else { var isCallback = ( typeof callbackName == 'string' ); // If a global callback name is given, then directly run removeJsListener if (isCallback) { player.removeJsListener(eventName, callbackName); } // If no callback was given, iterate over the list of listeners and remove all bindings per the given event name for (var eventNamespace in _this.listenerList) { for (var listenerItem in _this.listenerList[ eventNamespace ]) { if (listenerItem == eventName) { if (!isCallback) { player.removeJsListener(eventName, _this.listenerList[ eventNamespace ][ listenerItem ]); } delete _this.listenerList[ eventNamespace ][ listenerItem ]; } } } } } return player; } }, /** * Outputs a flash object into the page * * @param {string} targetId target container for iframe * @param {object} settings object used to build iframe settings */ outputFlashObject: function (targetId, settings, context) { context = context || document; var elm = context.getElementById(targetId); if (!elm && !elm.parentNode) { kWidget.log("Error embed target missing"); return; } // Only generate a swf source if not defined. if (!settings.src) { var swfUrl = mw.getConfig('Kaltura.ServiceUrl') + '/index.php/kwidget' + '/wid/' + settings.wid + '/uiconf_id/' + settings.uiconf_id; if (settings.entry_id) { swfUrl += '/entry_id/' + settings.entry_id; } if (settings.cache_st) { swfUrl += '/cache_st/' + settings.cache_st; } settings['src'] = swfUrl; } settings['id'] = elm.id; // update the container id: elm.setAttribute('id', elm.id + '_container'); // Output a normal flash object tag: var spanTarget = context.createElement("span"); // make sure flashvars are init: if (!settings.flashvars) { settings.flashvars = {}; } // Set our special callback flashvar: if (settings.flashvars['jsCallbackReadyFunc']) { kWidget.log("Error: Setting jsCallbackReadyFunc is not compatible with kWidget embed"); } // Check if in debug mode: if (mw.getConfig('debug', true)) { settings.flashvars['debug'] = true; } var flashvarValue = this.flashVarsToString(settings.flashvars); // we may have to borrow more from: // http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#407 // There seems to be issue with passing all the flashvars in playlist context. var defaultParamSet = { 'allowFullScreen': 'true', 'allowNetworking': 'all', 'allowScriptAccess': 'always', 'bgcolor': '#000000' }; // output css trim: var output = '<object style="' + elm.style.cssText.replace(/^\s+|\s+$/g, '') + ';display:block;" ' + ' class="' + elm.className + '" ' + ' id="' + targetId + '"' + ' name="' + targetId + '"'; output += ' data="' + settings['src'] + '" type="application/x-shockwave-flash"'; if (window.ActiveXObject) { output += ' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'; } output += '>'; output += '<param name="movie" value="' + settings['src'] + '" />'; output += '<param name="flashvars" value="' + flashvarValue + '" />'; // Output any custom params and let them override default params if (settings['params']) { for (var key in settings['params']) { if (defaultParamSet[key]) { defaultParamSet[key] = settings['params'][key]; } else { output += '<param name="' + key + '" value="' + settings['params'][key] + '" />'; } } } // output the default set of params for (var key in defaultParamSet) { if (defaultParamSet[key]) { output += '<param name="' + key + '" value="' + defaultParamSet[key] + '" />'; } } output += "</object>"; // Use local function to output contents to work around some browser bugs var outputElemnt = function () { // update the target: elm.parentNode.replaceChild(spanTarget, elm); spanTarget.innerHTML = output; } // XXX firefox with firebug enabled locks up the browser // detect firebug: if (window.console && ( window.console.firebug || window.console.exception )) { console.log('Warning firebug + firefox and dynamic flash kdp embed causes lockups in firefox' + ', ( delaying embed )'); this.domReady(function () { setTimeout(function () { outputElemnt(); }, 2000); }); } else { // IE needs to wait till dom ready if (navigator.userAgent.indexOf("MSIE") != -1) { setTimeout(function () { // MSIE fires DOM ready early sometimes outputElemnt(); }, 0); } else { outputElemnt(); } } }, createIframe: function(targetId, widgetElm){ var iframeId = widgetElm.id + '_ifp'; var iframeCssText = 'border:0px; max-width: 100%; max-height: 100%; width:100%;height:100%;'; var iframe = document.createElement("iframe"); iframe.id = iframeId; iframe.scrolling = "no"; iframe.name = iframeId; iframe.className = 'mwEmbedKalturaIframe'; iframe.setAttribute('title', 'The Kaltura Dynamic Video Player'); // IE8 requires frameborder attribute to hide frame border: iframe.setAttribute('frameborder', '0'); // Allow Fullscreen iframe.setAttribute('allowfullscreen', true); iframe.setAttribute('webkitallowfullscreen', true); iframe.setAttribute('mozallowfullscreen', true); // copy the target element css to the iframe proxy style: iframe.style.cssText = iframeCssText; // fix for iOS8 iframe overflow issue try { var iframeHeight = widgetElm.style.height ? widgetElm.style.height : widgetElm.offsetHeight; if (this.isIOS() && (parseInt(iframeHeight) > 0)) { iframe.style.height = iframeHeight; var updateIframeID = setTimeout(function(){ iframe.style.height = "100%"; },6000); window.addEventListener("message", function(event){ if ( event.data === 'layoutBuildDone' ){ iframe.style.height = "100%"; clearTimeout(updateIframeID); } }, false); } } catch (e) { this.log("Error when trying to set iframe height: " + e.message); } return iframe; }, createIframeProxy: function(widgetElm){ var iframeProxy = document.createElement("div"); iframeProxy.id = widgetElm.id; iframeProxy.name = widgetElm.name; var moreClass = widgetElm.className ? ' ' + widgetElm.className : ''; iframeProxy.className = 'kWidgetIframeContainer' + moreClass; // Update the iframe proxy style per org embed widget: iframeProxy.style.cssText = widgetElm.style.cssText + ';overflow: hidden'; return iframeProxy; }, createContentInjectCallback: function(cbName, iframe, iframeRequest, settings, ttlUnixVal){ var _this = this; // Do a normal async content inject: window[ cbName ] = function ( iframeData ) { var newDoc = iframe.contentWindow.document; if(_this.isFirefox()){ // in FF we have to pass the "replace" parameter to inherit the current history newDoc.open("text/html", "replace"); } else { newDoc.open(); } newDoc.write(iframeData.content); // TODO are we sure this needs to be on this side of the iframe? if ( mw.getConfig("EmbedPlayer.DisableContextMenu") ){ newDoc.getElementsByTagName('body')[0].setAttribute("oncontextmenu","return false;"); } newDoc.close(); if( _this.isInlineScriptRequest(settings) && kWidget.storage.isSupported()){ // if empty populate for the first time: var iframeStoredData = kWidget.storage.getWithTTL( iframeRequest ); if (iframeStoredData == null) { _this.cachePlayer(iframeRequest, iframeData.content, ttlUnixVal); } } // Clear out this global function window[cbName] = null; }; }, createContentUpdateCallback: function(cbName, iframeRequest, settings, ttlUnixVal, maxCacheEntries){ var _this = this; window[cbName] = function (iframeData) { // only populate the cache if request was an inlines scripts request. if (_this.isInlineScriptRequest(settings) && kWidget.storage.isSupported()) { _this.cachePlayer(iframeRequest, iframeData.content, ttlUnixVal); } // Clear out this global function window[cbName] = null; }; }, requestPlayer: function(iframeRequest, widgetElm, targetId, cbName, settings){ var _this = this; if ( iframeRequest.length > 2083 ){ //TODO:Need to output an error, cause we don't depend on jquery explicitly this.log( "Warning iframe requests (" + iframeRequest.length + ") exceeds 2083 charachters, won't cache on CDN." ); var url = this.getIframeUrl(); var requestData = iframeRequest; var isLowIE = document.documentMode && document.documentMode < 10; if ( isLowIE && settings.flashvars.jsonConfig ){ // -----> IE8 and IE9 hack to solve Studio issues. SUP-3795. Should be handled from PHP side and removed <---- jsonConfig = settings.flashvars.jsonConfig; delete settings.flashvars.jsonConfig; url += '?' + this.getIframeRequest(widgetElm, settings); requestData = {"jsonConfig": jsonConfig}; url += "&protocol=" + location.protocol.slice(0, -1); } else { url += "?protocol=" + location.protocol.slice(0, -1); } $.ajax({ type: "POST", dataType: 'text', url: url, data: requestData }) .success(function (data) { var contentData = {content: data}; window[cbName](contentData); }) .error(function (e) { _this.log("Error in player iframe request") }) } else { var iframeUrl = this.getIframeUrl() + '?' + iframeRequest; iframeUrl += "&protocol=" + location.protocol.slice(0, -1); // Store iframe urls this.iframeUrls[ targetId ] = iframeUrl; // do an iframe payload request: this.appendScriptUrl( iframeUrl +'&callback=' + cbName ); } }, isStorageMaxLimitExceeded: function(settings){ //Get max cache entries form user settings or use default var maxCacheEntries = settings.flashvars["Kaltura.MaxCacheEntries"]|| mw.getConfig("Kaltura.MaxCacheEntries"); var cacheEntriesCount = kWidget.storage.getEntriesCount(); return (cacheEntriesCount >= maxCacheEntries); }, cachePlayer: function(key, value, ttl){ var success = kWidget.storage.setWithTTL(key, value, ttl); if (success) { this.log("Player data stored in cache!"); } else { this.log("Error: unable to store Player data in cache!"); } }, /** * Output an html5 iframe player, once the html5 library is loaded * * @param {string} targetId target container for iframe * @param {object} settings object used to build iframe settings */ outputHTML5Iframe: function (targetId, settings) { var widgetElm = document.getElementById(targetId); var iframe = this.createIframe(targetId, widgetElm); // Create the iframe proxy that wraps the actual iframe // and will be converted into an "iframe" player via jQuery.fn.iFramePlayer call var iframeProxy = this.createIframeProxy(widgetElm); iframeProxy.appendChild(iframe); // Replace the player with the iframe: widgetElm.parentNode.replaceChild(iframeProxy, widgetElm); var requestSettings = JSON.parse(JSON.stringify(settings)); // Check if its a inline scripts setup: if( this.isInlineScriptRequest( requestSettings ) ){ // segment out all configuration requestSettings = this.getRuntimeSettings( requestSettings ); this.widgetOriginalSettings [widgetElm.id] = settings; mw.setConfig("widgetOriginalSettings_" + widgetElm.id, settings); } else { //If this is not an inlineScript request or we don't support it make sure to falsify it settings.flashvars['inlineScript'] = false; } // Check if we need to capture a play event ( iOS sync embed call ) if (settings.captureClickEventForiOS && (this.isSafari() || this.isAndroid())) { this.captureClickWrapedIframeUpdate(targetId, requestSettings, iframe); } else { // get the callback name: var cbName = this.getIframeCbName(targetId); var iframeRequest = this.getIframeRequest(widgetElm, requestSettings); //Get TTL for cache entries form user settings or use default var ttlUnixVal = settings.flashvars["Kaltura.CacheTTL"] || mw.getConfig("Kaltura.CacheTTL"); //Prepare an iframe content injection hook this.createContentInjectCallback(cbName, iframe, iframeRequest, requestSettings, ttlUnixVal); // Try and get playload from local cache ( autoEmbed ) if (this.iframeAutoEmbedCache[targetId]) { window[cbName](this.iframeAutoEmbedCache[targetId]); } else { // try to get payload from localStorage cache var iframeData = null; if (kWidget.storage.isSupported()) { iframeData = kWidget.storage.getWithTTL(iframeRequest); } //If iframe content is in cache then load it immediately and update from server for next time if (!mw.getConfig('debug') && iframeData && iframeData != "null") { window[cbName]({'content': iframeData}); // we don't retrun here, instead we run the get request to update the uiconf storage // TODO this should just be a 304 check not a full download of the iframe ( normally ) // RETURN UNTIL WE HAVE 30$ check in palce. //return ; cbName += "updateAsync"; // after loading iframe, prepare a content update hook this.createContentUpdateCallback(cbName, iframeRequest, requestSettings, ttlUnixVal); } //Enforce the max storage entries setting to avoid over populating the localStorage if (kWidget.storage.isSupported() && this.isStorageMaxLimitExceeded(settings)) { kWidget.storage.clearNS(); } // Do a normal async content inject/update request: this.requestPlayer(iframeRequest, widgetElm, targetId, cbName, requestSettings); } } }, /** * Returns the callback name for an iframe */ getIframeCbName: function (iframeId) { var _this = this; var inx = 0; var baseCbName = 'mwi_' + iframeId.replace(/[^0-9a-zA-Z]/g, ''); var cbName = baseCbName + inx; while (window[ cbName ]) { _this.log("Warning: iframe callback already defined: " + cbName); inx++; cbName = baseCbName + inx; } return cbName; }, // TODO does this need to be part of the kWidget library? resizeOvelayByHolderSize: function (overlaySize, parentSize, ratio) { var overlayRatio = overlaySize.width / overlaySize.height; var centeredParent = { 'width' : parentSize.width * ratio, 'height' : parentSize.height * ratio }; var diffs = { 'width' : parentSize.width - overlaySize.width, 'height' : parentSize.height - overlaySize.height }; var screenSize = { 'width' : 0, 'height' : 0 }; // Image size smaller then then the videoHolder size if (diffs.width > 0 && diffs.height > 0) { screenSize.width = overlaySize.width; screenSize.height = overlaySize.height; // Image height bigger or equals to video holder height and image width is smaller } else if (diffs.width > 0 && diffs.height <= 0) { screenSize.height = centeredParent.height; screenSize.width = screenSize.height * overlayRatio; // Image width bigger or equals to video holder width and image height is smaller } else if (diffs.width <= 0 && diffs.height > 0) { screenSize.width = centeredParent.width; screenSize.height = screenSize.width / overlayRatio; // Image size bigger then video holder size } else if (diffs.width <= 0 && diffs.height <=0) { // Check which value is bigger to use the biggest ratio if (diffs.width <= diffs.height) { screenSize.width = centeredParent.width; screenSize.height = screenSize.width / overlayRatio; } else { screenSize.height = centeredParent.height; screenSize.width = screenSize.height * overlayRatio; } } return screenSize; }, /** * Supports the iOS captured clicks iframe update, * * Inserts a video tag synchronously into the iframe, ( pointed to black video file ) * Issues play on the iframe video tag * Issues async request to grab iframe data with "no video tag" * Runs script blocks and allows iframe to update persistent video tag. * * @param {String} targetId The target id to be updated * @param {Object} settings The embed Settings object * @param {Element} iframeElm The target iframe element the page. */ captureClickWrapedIframeUpdate: function (targetId, settings, iframeElm) { var _this = this; var widgetElm = document.getElementById(targetId); var newDoc = iframeElm.contentDocument; newDoc.open(); // grab a black source var vidSrc = location.protocol + '//www.kaltura.com/p/243342/sp/24334200/playManifest/entryId/1_vp5cng42/flavorId/1_6wf0o9n7/format/url/protocol/http/a.mp4'; // Add the iframe skeleton with video element to the iframe newDoc.write('<html>' + '<head></head>' + '<body>' + '<div class="mwPlayerContainer" style="width: 100%; height: 100%">' + '<div class="videoHolder">' + '<video class="persistentNativePlayer" ' + 'id="' + targetId + '" ' + 'kwidgetid="' + settings.wid + '" ' + 'kentryid="' + settings.entry_id + '" ' + 'kuiconfid="' + settings.uiconf_id + '" ' + //'poster="' + _this.getKalturaThumbUrl( settings ) + '" ' + // Only applies to iOS, and only to caputre the play event, // so we only include a low bitrate mp4 'src="' + vidSrc + '" ' + 'style="width:100%;height:100%" ' + '>' + '</video>' + '</div>' + '</div>' + // issue play on the silent black video ( to capture iOS gesture ) '<scr'+'ipt>document.getElementById(\'' + targetId + '\').play();</scr'+'ipt>' + '<div id="scriptsHolder"></div>' + '</body>' + '</html>' ); newDoc.close(); // get the callback name: var cbName = this.getIframeCbName(targetId); // Else do a normal async include: window[ cbName ] = function (iframeParts) { // update the header: var head = iframeElm.contentDocument.getElementsByTagName("head")[0] || iframeElm.documentElement; head.innerHTML = iframeParts.rawHead; // append the scripts: iframeElm.contentDocument.getElementById("scriptsHolder").innerHTML = iframeParts.rawScripts; var nodeName = function (elem, name) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); } // eval a script in the iframe context var evalScript = function (elem) { var data = ( elem.text || elem.textContent || elem.innerHTML || "" ); var head = iframeElm.contentDocument.getElementsByTagName("head")[0] || iframeElm.documentElement; var script = iframeElm.contentDocument.createElement("script"); script.type = "text/javascript"; script.appendChild(document.createTextNode(data)); head.insertBefore(script, head.firstChild); //head.removeChild( script ); if (elem.parentNode) { elem.parentNode.removeChild(elem); } } var scripts = []; var headElm = head.childNodes; //var ret = iframeElm.contentDocument.body.childNodes; var ret = iframeElm.contentDocument.getElementById("scriptsHolder").childNodes; for (var i = 0; ret[i]; i++) { if (scripts && nodeName(ret[i], "script") && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript")) { scripts.push(ret[i].parentNode ? ret[i].parentNode.removeChild(ret[i]) : ret[i]); } } // eval all the raw scripts for (var script in scripts) { evalScript(scripts[ script ]); } }; // Add the iframe script: _this.appendScriptUrl(this.getIframeUrl() + '?' + this.getIframeRequest(widgetElm, settings) + '&callback=' + cbName + '&parts=1'); }, isInlineScriptRequest: function( settings ){ // don't inline scripts in debug mode: if( mw.getConfig('debug') || this.isMobileDevice()){ return false; } // check for inlineScript flag: if( settings.flashvars['inlineScript'] ){ return true; } return false; }, // retruns only the runtime config getRuntimeSettings: function( settings ){ var runtimeSettings = {}; var allowedVars = mw.getConfig('Kaltura.AllowedVars'); allowedVars = allowedVars.split(","); var allowedVarsKeyPartials = mw.getConfig('Kaltura.AllowedVarsKeyPartials'); allowedVarsKeyPartials = allowedVarsKeyPartials.split(","); var allowedPluginVars = mw.getConfig('Kaltura.AllowedPluginVars'); allowedPluginVars = allowedPluginVars.split(","); var allowedPluginVarsValPartials = mw.getConfig('Kaltura.AllowedPluginVarsValPartials'); allowedPluginVarsValPartials = allowedPluginVarsValPartials.split(","); for( var settingsKey in settings ){ // entry id should never be included ( hurts player iframe cache ) if( settingsKey == 'entry_id' ){ continue; } if( settingsKey =='flashvars' ){ // add flashvars container: var runtimeFlashvars = runtimeSettings[settingsKey] = {}; var flashvars = settings[settingsKey]; for( var flashvarKey in flashvars ){ if( typeof flashvars[flashvarKey] != 'object' ) { var flashvar = flashvars[flashvarKey]; // Special Case a few flashvars that are always copied to iframe: if ([].indexOf.call(allowedVars, flashvarKey, 0) > -1) { runtimeFlashvars[flashvarKey] = flashvar; continue; } // Special case vars that require server side template substations for (var idx in allowedVarsKeyPartials) { if (flashvarKey.indexOf(allowedVarsKeyPartials[idx]) > -1) { runtimeFlashvars[flashvarKey] = flashvar; continue; } } } if( typeof flashvars[flashvarKey] == 'object' ){ // Set an empty plugin if any value is preset ( note this means .plugin=false overrides do still load the plugin // but this is "OK" because the client is likely setting this at runtime on purpose. Its more value // to get a cache hit all time time independently of alerting enabled/disabled flag. // Plugin diablement will still be read during runtime player build-out. var runtimePlugin = runtimeFlashvars[flashvarKey]={}; var plugin = flashvars[flashvarKey]; for( var pluginKey in plugin ) { var pluginVal = plugin[pluginKey]; // Special Case a few flashvars that are always copied to iframe: if ([].indexOf.call( allowedPluginVars, pluginKey, 0 ) > -1) { runtimePlugin[pluginKey] = pluginVal; continue; } if (typeof pluginVal == "string") { // Special case vars that require server side template substations for (var idx in allowedPluginVarsValPartials) { if (pluginVal.indexOf(allowedPluginVarsValPartials[idx]) > -1){ runtimePlugin[pluginKey] = plugin[pluginKey]; continue; } } } } } } // don't do high level copy of flashvars continue; } runtimeSettings[ settingsKey ] = settings[settingsKey]; } return runtimeSettings; }, /** * Build the iframe request from supplied settings: */ getIframeRequest: function (elm, settings) { // Get the base set of kaltura params ( entry_id, uiconf_id etc ) var iframeRequest = this.embedSettingsToUrl( settings ); // Add the player id: iframeRequest += '&playerId=' + elm.id; // Add &debug is in debug mode if (mw.getConfig('debug')) { iframeRequest += '&debug=true'; } // add ps if set: if (mw.getConfig('Kaltura.KWidgetPsPath')) { iframeRequest += '&pskwidgetpath=' + mw.getConfig('Kaltura.KWidgetPsPath'); } // If remote service is enabled pass along service arguments: if (mw.getConfig('Kaltura.AllowIframeRemoteService') && ( mw.getConfig("Kaltura.ServiceUrl").indexOf('kaltura.com') === -1 && mw.getConfig("Kaltura.ServiceUrl").indexOf('kaltura.org') === -1 ) ) { iframeRequest += kWidget.serviceConfigToUrl(); } // Add no cache flag if set: if (mw.getConfig('Kaltura.NoApiCache')) { iframeRequest += '&nocache=true'; } if (this.isUiConfIdHTML5(settings.uiconf_id)) { iframeRequest += '&forceMobileHTML5=true'; } // Also append the script version to purge the cdn cache for iframe: iframeRequest += '&urid=' + MWEMBED_VERSION; return iframeRequest; }, getIframeUrl: function () { var path = this.getPath(); if (mw.getConfig('Kaltura.ForceIframeEmbed') === true) { // In order to simulate iframe embed we need to use different host path = path.replace('localhost', '127.0.0.1'); } return path + 'mwEmbedFrame.php'; }, getPath: function () { return SCRIPT_LOADER_URL.replace('load.php', ''); }, /** * Output an iframe without api. ( should rarely be used, this disable on page javascript api, * as well as native fullscreen on browsers that support it. * * @param {string} replaceTargetId target container for iframe * @param {object} kEmbedSettings object used to build iframe settings */ outputIframeWithoutApi: function (targetId, settings) { var targetEl = document.getElementById(targetId); var iframeSrc = this.getIframeUrl() + '?' + this.getIframeRequest(targetEl, settings) + '&iframeembed=true'; var targetNode = document.getElementById(targetId); var parentNode = targetNode.parentNode; var iframe = document.createElement('iframe'); iframe.src = iframeSrc; iframe.id = targetId; iframe.width = (settings.width) ? settings.width.replace(/px/, '') : '100%'; iframe.height = (settings.height) ? settings.height.replace(/px/, '') : '100%'; iframe.className = targetNode.className ? ' ' + targetNode.className : ''; // Update the iframe proxy style per org embed widget: iframe.style.cssText = targetNode.style.cssText; iframe.style.border = '0px'; iframe.style.overflow = 'hidden'; parentNode.replaceChild(iframe, targetNode); }, /** * Adds a ready callback to be called once the kdp or html5 player is ready * @param {function} readyCallback called once a player or widget is ready on the page */ addReadyCallback: function (readyCallback) { // Issue the ready callback for any existing ready widgets: for (var widgetId in this.readyWidgets) { // Make sure the widget is not already ready and is still in the dom: if (document.getElementById(widgetId)) { readyCallback(widgetId); } } // Add the callback to the readyCallbacks array for any other players that become ready this.readyCallbacks.push(readyCallback); // Make sure we proxy the ready callback: this.proxyJsCallbackready(); }, /** * Search the DOM for Object tags and rewrite them if they should be rewritten. * * rewrite rules include: * - userAgentRules -- may result in loading uiConf rewrite rules * - forceMobileHTML5 -- a url flag to force HTML5 for testing, can be disabled on iframe side, * per uiConf vars * - ForceFlashOnDesktop -- forces flash for desktop browsers. */ rewriteObjectTags: function () { // get the list of object tags to be rewritten: var playerList = this.getKalutaObjectList(); var _this = this; // don't bother with checks if no players exist: if (!playerList.length) { this.playerModeChecksDone(); return; } // Check if we need to load UiConf JS if (this.isMissingUiConfJs(playerList)) { // Load uiConfJS then re call the rewriteObjectTags method: this.loadUiConfJs(playerList, function () { _this.rewriteObjectTags(); }) return; } /** * If Kaltura.AllowIframeRemoteService is not enabled force in page rewrite: */ var serviceUrl = mw.getConfig('Kaltura.ServiceUrl'); if (!mw.getConfig('Kaltura.AllowIframeRemoteService')) { if (!serviceUrl || serviceUrl.indexOf('kaltura.com') === -1) { // if not hosted on kaltura for now we can't use the iframe to load the player mw.setConfig('Kaltura.IframeRewrite', false); mw.setConfig('Kaltura.UseManifestUrls', false); } } /* * TODO revisit support for video tag rewrites ( maybe redirect to iframe style embed ) if( ! mw.getConfig( 'Kaltura.ForceFlashOnDesktop' ) && ( mw.getConfig( 'Kaltura.LoadScriptForVideoTags' ) && this.pageHasAudioOrVideoTags() ) ){ loadHTML5LibAndRewriteTags(); return ; } */ // check for global lead with html5: if (this.isHTML5FallForward()) { this.embedFromObjects(playerList); return; } // loop over the playerList check if given uiConf should be lead with html: for (var i = 0; i < playerList.length; i++) { if (this.isUiConfIdHTML5(playerList[i].kEmbedSettings['uiconf_id'])) { this.embedFromObjects([ playerList[i] ]); } } // Check if no flash and no html5 and no forceFlash ( direct download link ) if (!this.supportsFlash() && !this.supportsHTML5() && !mw.getConfig('Kaltura.ForceFlashOnDesktop')) { this.embedFromObjects(playerList); return; } this.playerModeChecksDone(); }, // Global instance of uiConf ids and associated script loaded state uiConfScriptLoadList: {}, /** * Stores a callback for inLoadJs ( replaced by direct callback if that is all the players we are worried about ) */ // flag for done loading uiConfJs inLoaderUiConfJsDone: false, inLoaderUiConfJsCallbackSet: [], inLoaderUiConfJsCallback: function () { this.inLoaderUiConfJsDone = true; while (this.inLoaderUiConfJsCallbackSet.length) { this.inLoaderUiConfJsCallbackSet.shift()(); } }, /** * Check if any player is missing uiConf javascript: * @param {object} playerList List of players to check for missing uiConf js */ isMissingUiConfJs: function (playerList) { // Check if we are waiting for inLoader uiconf js: if (this.inLoaderUiConfJsDone == false) { return true; } // Check if we need to load uiConfJs ( for non-inLoaderUiConfJs ) if (playerList.length == 0 || !mw.getConfig('Kaltura.EnableEmbedUiConfJs') || mw.getConfig('EmbedPlayer.IsIframeServer')) { return false; } for (var i = 0; i < playerList.length; i++) { var settings = playerList[i].kEmbedSettings; if (!this.uiConfScriptLoadList[ settings.uiconf_id ]) { return true; } } return false; }, uiConfScriptLoadListCallbacks: {}, /** * Loads the uiConf js for a given playerList * @param {object} playerList list of players to check for uiConf js * @param {function} callback, called once all uiConf service calls have been made */ loadUiConfJs: function (playerList, doneCallback) { var _this = this; // Check if we cover all uiConfs via inLoaderUiConfJs var callback = function () { // check if the done flag has been set: if (_this.inLoaderUiConfJsDone) { doneCallback() } else { // replace the callback _this.inLoaderUiConfJsCallbackSet.push(doneCallback); } return; } // We have not yet loaded uiConfJS... load it for each ui_conf id var baseUiConfJsUrl = this.getPath() + 'services.php?service=uiconfJs'; // add ps if set: if (mw.getConfig('Kaltura.KWidgetPsPath')) { baseUiConfJsUrl += '&pskwidgetpath=' + mw.getConfig('Kaltura.KWidgetPsPath'); } if (!this.isMissingUiConfJs(playerList)) { // called with empty request set: callback(); return; } var foundPlayerMissingUiConfJs = false; for (var i = 0; i < playerList.length; i++) { // Create a local scope for the current uiconf_id: (function (settings) { if (_this.uiConfScriptLoadList[ settings.uiconf_id ]) { // player ui conf js is already loaded skip: return; } foundPlayerMissingUiConfJs = true; // Setup uiConf callback so we don't risk out of order execution var cbName = 'kUiConfJs_' + i + '_' + settings.uiconf_id; if (!_this.uiConfScriptLoadListCallbacks[ cbName ]) { _this.uiConfScriptLoadListCallbacks[ cbName ] = [ callback ]; window[ cbName ] = function () { _this.uiConfScriptLoadList[ settings.uiconf_id ] = true; // issue all uiConfScriptLoad callbacks: for (var inx in _this.uiConfScriptLoadListCallbacks[ cbName ]) { if (_this.uiConfScriptLoadListCallbacks[ cbName ].hasOwnProperty(inx) && typeof _this.uiConfScriptLoadListCallbacks[ cbName ][inx] == 'function') { _this.uiConfScriptLoadListCallbacks[ cbName ][inx](); } } ; }; // add the services.php includes: var scriptUrl = baseUiConfJsUrl + _this.embedSettingsToUrl(settings) + '&callback=' + cbName; if (scriptUrl.length > 4096){ _this.log( "Warning iframe requests (" + scriptUrl.length + ") exceeds 4096 characters, won't cache on CDN." ) $.ajax({ type: "POST", dataType: 'text', url: _this.getIframeUrl(), data: _this.embedSettingsToUrl(settings) }).success(function (data) { var contentData = {content: data}; window[cbName](contentData); }) .error(function (e) { _this.log("Error in player iframe request"); }); }else{ _this.appendScriptUrl(scriptUrl); } } else { // add the callback _this.uiConfScriptLoadListCallbacks[ cbName ].push(callback); } })(playerList[i].kEmbedSettings); } // check if we should wait for a player to load its uiConf: if (!foundPlayerMissingUiConfJs) { callback(); return; } }, /** * Write log message to the console * TODO support log levels: https://github.com/kaltura/mwEmbed/issues/80 */ log: function (msg) { // only log if debug is active: if (typeof mw != 'undefined' && !mw.getConfig('debug')) { return; } if (typeof console != 'undefined' && console.log) { if (this.isIE8()){ try{ console.log("kWidget: " + msg); }catch(e){} }else{ console.log("kWidget: " + msg); } } }, /** * If the current player supports html5: * @return {boolean} true or false if HTML5 video tag is supported */ supportsHTML5: function () { if (mw.getConfig('EmbedPlayer.DisableVideoTagSupport')) { return false; } var dummyvid = document.createElement("video"); if (dummyvid.canPlayType) { return true; } return false; }, supportsHTMLPlayerUI: function () { return this.supportsHTML5() || (this.isIE8() && this.supportsFlash()); }, /** * If the browser supports flash * @return {boolean} true or false if flash > 10 is supported. */ supportsFlash: function () { if (mw.getConfig('EmbedPlayer.DisableHTML5FlashFallback')) { return false; } var version = this.getFlashVersion().split(',').shift(); if (version < 10) { return false; } else { return true; } }, /** * Checks for flash version * @return {string} flash version string */ getFlashVersion: function () { // navigator browsers: if (navigator.plugins && navigator.plugins.length) { try { if (navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) { return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1]; } } catch (e) { } } // IE try { try { if (typeof ActiveXObject != 'undefined') { // avoid fp6 minor version lookup issues // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/ var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6'); try { axo.AllowScriptAccess = 'always'; } catch (e) { return '6,0,0'; } } } catch (e) { } return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } catch (e) { } return '0,0,0'; }, /** * Checks for iOS devices **/ isIOS: function () { return ( (navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1) ); }, isFirefox: function(){ return navigator.userAgent.indexOf('Firefox') != -1; }, isIE: function () { return /\bMSIE\b/.test(navigator.userAgent); }, isIE8: function () { return document.documentMode === 8; }, isAndroid: function () { return (navigator.userAgent.indexOf('Android ') !== -1 && navigator.userAgent.indexOf('Windows') === -1); }, isWindowsDevice: function () { var appVer = navigator.appVersion; return ((appVer.indexOf("Win") != -1 && (navigator.appVersion.indexOf("Phone") != -1 || navigator.appVersion.indexOf("CE") != -1))); }, /** * Checks for mobile devices **/ isMobileDevice: function () { return (this.isIOS() || this.isAndroid() || this.isWindowsDevice() || mw.getConfig("EmbedPlayer.ForceNativeComponent") || mw.getConfig("EmbedPlayer.SimulateMobile") === true ); }, isChromeCast: function(){ return (/CrKey/.test(navigator.userAgent)); }, /** * Checks if a given uiconf_id is html5 or not * @param {string} uiconf_id The uiconf id to check against user player agent rules */ isUiConfIdHTML5: function (uiconf_id) { var isHTML5 = this.isHTML5FallForward(); if (this.userAgentPlayerRules && this.userAgentPlayerRules[ uiconf_id ]) { var playerAction = this.checkUserAgentPlayerRules(this.userAgentPlayerRules[ uiconf_id ]); if (playerAction.mode == 'leadWithHTML5') { isHTML5 = this.supportsHTMLPlayerUI(); } } return isHTML5; }, /** * Fallforward by default prefers flash, uses html5 only if flash is not installed or not available */ isHTML5FallForward: function () { // Check for a mobile html5 user agent: if (this.isIOS() || mw.getConfig('forceMobileHTML5')) { return true; } // Check for "Kaltura.LeadWithHTML5" attribute // Only return true if the browser actually supports html5 if ( ( mw.getConfig('KalturaSupport.LeadWithHTML5') || mw.getConfig('Kaltura.LeadWithHTML5') ) && this.supportsHTMLPlayerUI() ) { return true; } // Special check for Android: if (this.isAndroid()) { if (mw.getConfig('EmbedPlayer.UseFlashOnAndroid') && kWidget.supportsFlash() ) { // Use flash on Android if available return false; } else { // Some Android supports the video tag return true; } } /** * If the browser supports flash ( don't use html5 ) * On ModernUI IE10, Flash is integrated. However, our Flash detection on IE looks for ActiveX which is disabled, thus failing. */ if (kWidget.supportsFlash()) { return false; } /** * Allow forcing flash on IE10 * Since we don't check Microsoft's CV list, we cannot say whether a domain has been whitelisted for Flash or not. * Due to that, we fallback to HTML5 player on Modern UI IE10 by default * Using this flag this can be overriden. */ if (mw.getConfig('Kaltura.ForceFlashOnIE10')) { var ua = navigator.userAgent; var ie10Match = document.documentMode === 10; if (ie10Match) { return false; } } // Check if the UseFlashOnDesktop flag is set and ( don't check for html5 ) if (mw.getConfig('Kaltura.ForceFlashOnDesktop')) { return false; } // No flash return true if the browser supports html5 video tag with basic support for canPlayType: if (kWidget.supportsHTML5()) { return true; } // if we have the iframe enabled return true ( since the iframe will output a fallback link // even if the client does not support html5 or flash ) if (mw.getConfig('Kaltura.IframeRewrite')) { return true; } // No video tag or flash, or iframe, normal "install flash" user flow ) return false; }, getDownloadLink: function (settings) { var _this = this; // update the settings object var baseUrl = _this.getPath(); var downloadUrl = baseUrl + 'modules/KalturaSupport/download.php/wid/' + settings.wid; // Also add the uiconf id to the url: if (settings.uiconf_id) { downloadUrl += '/uiconf_id/' + settings.uiconf_id; } if (settings.entry_id) { downloadUrl += '/entry_id/' + settings.entry_id; } var flashVarsString = this.flashVarsToString(settings.flashvars); var ks = settings.ks; if (ks) { downloadUrl += '/?ks=' + ks + flashVarsString; } else { downloadUrl += '/?' + flashVarsString.substr(1, flashVarsString.length); } return downloadUrl; }, /** * Get Kaltura thumb url from entry object * TODO We need to grab thumbnail path from api (baseEntry->thumbnailUrl) * or a specialized entry point for cases where we don't have the api is available * * @param {object} Entry settings used to generate the api url request */ getKalturaThumbUrl: function (settings) { //Check if external thumbnailUrl is defined if (settings.flashvars && settings.flashvars.thumbnailUrl !== undefined){ return settings.flashvars.thumbnailUrl; } var sizeParam = ''; if (settings.width != '100%' && settings.width) { sizeParam += '/width/' + parseInt(settings.width); } if (settings.height != '100%' && settings.height) { sizeParam += '/height/' + parseInt(settings.height); } // if no height or width is provided default to 480P if (!settings.height && !settings.width) { sizeParam += '/height/480'; } var vidParams = ''; if (settings.vid_sec) { vidParams += '/vid_sec/' + settings.vid_sec; } if (settings.vid_slices) { vidParams += '/vid_slices/' + settings.vid_slices; } // Add the ks if set ( flashvar overrides settings based ks ) if (settings.ks) { vidParams+= '/ks/' + settings.ks; } if (settings.flashvars && settings.flashvars.ks) { vidParams+= '/ks/' + settings.flashvars.ks; } var flashVars = {}; // Add referenceId if set if (settings.flashvars && settings.flashvars.referenceId) { flashVars[ 'referenceId' ] = settings.flashvars.referenceId; } if (settings.p && !settings.partner_id) { settings.partner_id = settings.p; } if (!settings.partner_id && settings.wid) { //this.log("Warning, please include partner_id in your embed settings"); settings.partner_id = settings.wid.replace('_', ''); } // Check for entryId var entryId = (settings.entry_id) ? '/entry_id/' + settings.entry_id : ''; // Return the thumbnail.php script which will redirect to the thumbnail location return this.getPath() + 'modules/KalturaSupport/thumbnail.php' + '/p/' + settings.partner_id + '/uiconf_id/' + settings.uiconf_id + entryId + sizeParam + vidParams + '?' + this.flashVarsToUrl(flashVars); }, /** * Get kaltura embed settings from a swf url and flashvars object * * @param {string} swfUrl * url to kaltura platform hosted swf * @param {object} flashvars * object mapping kaltura variables, ( overrides url based variables ) */ getEmbedSettings: function (swfUrl, flashvars) { var embedSettings = {}; // Convert flashvars if in string format: if (typeof flashvars == 'string') { flashvars = this.flashVars2Object(flashvars); } if (!flashvars) { flashvars = {}; } if (!swfUrl) { return {}; } var trim = function (str) { return str.replace(/^\s+|\s+$/g, ""); } // Include flashvars embedSettings.flashvars = flashvars; var dataUrlParts = swfUrl.split('/'); // Search backward for key value pairs var prevUrlPart = null; while (dataUrlParts.length) { var curUrlPart = dataUrlParts.pop(); switch (curUrlPart) { case 'p': embedSettings.wid = '_' + prevUrlPart; embedSettings.p = prevUrlPart; break; case 'wid': embedSettings.wid = prevUrlPart; embedSettings.p = prevUrlPart.replace(/_/, ''); break; case 'entry_id': embedSettings.entry_id = prevUrlPart; break; case 'uiconf_id': case 'ui_conf_id': embedSettings.uiconf_id = prevUrlPart; break; case 'cache_st': embedSettings.cache_st = prevUrlPart; break; } prevUrlPart = trim(curUrlPart); } // Add in Flash vars embedSettings ( they take precedence over embed url ) for (var key in flashvars) { var val = flashvars[key]; key = key.toLowerCase(); // Normalize to the url based settings: if (key == 'entryid') { embedSettings.entry_id = val; } if (key == 'uiconfid') { embedSettings.uiconf_id = val; } if (key == 'widgetid' || key == 'widget_id') { embedSettings.wid = val; } if (key == 'partnerid' || key == 'partner_id') { embedSettings.wid = '_' + val; embedSettings.p = val; } if (key == 'referenceid') { embedSettings.reference_id = val; } } // Always pass cache_st if (!embedSettings.cache_st) { embedSettings.cache_st = 1; } return embedSettings; }, /** * Converts a flashvar string to flashvars object * @param {String} flashvarsString * @return {Object} flashvars object */ flashVars2Object: function (flashvarsString) { var flashVarsSet = ( flashvarsString ) ? flashvarsString.split('&') : []; var flashvars = {}; for (var i = 0; i < flashVarsSet.length; i++) { var currentVar = flashVarsSet[i].split('='); if (currentVar[0] && currentVar[1]) { flashvars[ currentVar[0] ] = currentVar[1]; } } return flashvars; }, /** * Convert flashvars to a string * @param {object} flashVarsObject object to be string encoded */ flashVarsToString: function (flashVarsObject) { var params = ''; for (var i in flashVarsObject) { // check for object representation of plugin config: if (typeof flashVarsObject[i] == 'object') { for (var j in flashVarsObject[i]) { params += '&' + '' + encodeURIComponent(i) + '.' + encodeURIComponent(j) + '=' + encodeURIComponent(flashVarsObject[i][j]); } } else { params += '&' + '' + encodeURIComponent(i) + '=' + encodeURIComponent(flashVarsObject[i]); } } return params; }, /** * Converts a flashvar object into a url object string * @param {object} flashVarsObject object to be url encoded */ flashVarsToUrl: function (flashVarsObject) { var params = ''; for (var i in flashVarsObject) { var curVal = typeof flashVarsObject[i] == 'object'? JSON.stringify( flashVarsObject[i] ): flashVarsObject[i]; params += '&' + 'flashvars[' + encodeURIComponent(i) + ']=' + encodeURIComponent(curVal); } return params; }, /** * @return {boolean} true if page has audio video tags */ pageHasAudioOrVideoTags: function () { // if selector is set to false or is empty return false if (mw.getConfig('EmbedPlayer.RewriteSelector') === false || mw.getConfig('EmbedPlayer.RewriteSelector') == '') { return false; } // If document includes audio or video tags if (document.getElementsByTagName('video').length != 0 || document.getElementsByTagName('audio').length != 0) { return true; } return false; }, /** * Get the list of embed objects on the page that are 'kaltura players' */ getKalutaObjectList: function () { var _this = this; var kalturaPlayerList = []; // Check all objects for kaltura compatible urls var objectList = document.getElementsByTagName('object'); if (!objectList.length && document.getElementById('kaltura_player')) { objectList = [ document.getElementById('kaltura_player') ]; } // local function to attempt to add the kalturaEmbed var tryAddKalturaEmbed = function (url, flashvars) { //make sure we change only kdp objects if (!url.match(/(kwidget|kdp)/ig)) { return false; } var settings = _this.getEmbedSettings(url, flashvars); if (settings && settings.uiconf_id && settings.wid) { objectList[i].kEmbedSettings = settings; kalturaPlayerList.push(objectList[i]); return true; } return false; }; for (var i = 0; i < objectList.length; i++) { if (!objectList[i]) { continue; } var swfUrl = ''; var flashvars = {}; var paramTags = objectList[i].getElementsByTagName('param'); for (var j = 0; j < paramTags.length; j++) { var pName = paramTags[j].getAttribute('name').toLowerCase(); var pVal = paramTags[j].getAttribute('value'); if (pName == 'data' || pName == 'src' || pName == 'movie') { swfUrl = pVal; } if (pName == 'flashvars') { flashvars = this.flashVars2Object(pVal); } } if (tryAddKalturaEmbed(swfUrl, flashvars)) { continue; } // Check for object data style url: if (objectList[i].getAttribute('data')) { if (tryAddKalturaEmbed(objectList[i].getAttribute('data'), flashvars)) { continue; } } } return kalturaPlayerList; }, /** * Checks if the current page has jQuery defined, else include it and issue callback */ jQueryLoadCheck: function (callback) { if (!window.jQuery || !mw.versionIsAtLeast("1.7.2", window.jQuery.fn.jquery)) { // Set clientPagejQuery if already defined, if (window.jQuery) { window.clientPagejQuery = window.jQuery.noConflict(); // keep client page jQuery in $ window.$ = window.clientPagejQuery; } this.appendScriptUrl(this.getPath() + 'resources/jquery/jquery.min.js', function () { // remove jQuery from window scope if client has already included older jQuery window.kalturaJQuery = window.jQuery.noConflict(); // Restore client jquery to base target if (window.clientPagejQuery) { window.jQuery = window.$ = window.clientPagejQuery; } // Run all on-page code with kalturaJQuery scope // ( pass twice to poupluate $, and jQuery ) callback(window.kalturaJQuery, window.kalturaJQuery); }); } else { // update window.kalturaJQuery reference: window.kalturaJQuery = window.jQuery; callback(window.jQuery, window.jQuery); } }, // similar to jQuery.extend extend: function (obj) { var argSet = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < argSet.length; i++) { var source = argSet[i]; if (source) { for (var prop in source) { if (source[prop] && source[prop].constructor === Object) { if (!obj[prop] || obj[prop].constructor === Object) { obj[prop] = obj[prop] || {}; this.extend(obj[prop], source[prop]); } else { obj[prop] = source[prop]; } } else { obj[prop] = source[prop]; } } } } ; return obj; }, // similar to parm param: function (obj) { var o = ''; var and = ''; for (var i in obj) { o += and + i + '=' + encodeURIComponent(obj[i]); and = '&'; } return o; }, /** * Append a set of urls, and issue the callback once all have been loaded * @param {array} urls * @param {function} callback */ appendScriptUrls: function (urls, callback) { kWidget.log("appendScriptUrls"); var _this = this; var loadCount = 0; if (urls.length == 0) { if (callback) callback(); return; } for (var i = 0; i < urls.length; i++) { (function (inx) { _this.appendScriptUrl(urls[inx], function () { loadCount++; if (loadCount == urls.length) { if (callback) callback(); } }) })(i); } }, /** * Append a script to the dom: * @param {string} url * @param {function} done callback * @param {object} Document to append the script on * @param {function} error callback */ appendScriptUrl: function (url, callback, docContext, callbackError) { if (!docContext) { docContext = window.document; } var head = docContext.getElementsByTagName("head")[0] || docContext.documentElement; var script = docContext.createElement("script"); script.src = url; // Handle Script loading var done = false; // Attach handlers for all browsers script.onload = script.onerror = script.onreadystatechange = function () { if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) { done = true; if (arguments && arguments[0] && arguments[0].type) { if (arguments[0].type == "error") { if (typeof callbackError == "function") { callbackError(); } } else { if (typeof callback == "function") { callback(); } } } else { if (typeof callback == "function") { callback(); } } // Handle memory leak in IE script.onload = script.onerror = script.onreadystatechange = null; if (head && script.parentNode) { head.removeChild(script); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore(script, head.firstChild); }, /** * Add css to the dom * @param {string} url to append to the dom */ appendCssUrl: function (url, context) { context = context || document; var head = context.getElementsByTagName("head")[0]; var cssNode = context.createElement('link'); cssNode.setAttribute("rel", "stylesheet"); cssNode.setAttribute("type", "text/css"); cssNode.setAttribute("href", url); // cssNode.setAttribute("media","screen"); head.appendChild(cssNode); }, /** * Converts service configuration to url params */ serviceConfigToUrl: function () { var serviceVars = ['ServiceUrl', 'CdnUrl', 'ServiceBase', 'UseManifestUrls']; var urlParam = ''; for (var i = 0; i < serviceVars.length; i++) { if (mw.getConfig('Kaltura.' + serviceVars[i]) !== null) { urlParam += '&' + serviceVars[i] + '=' + encodeURIComponent(mw.getConfig('Kaltura.' + serviceVars[i])); } } return urlParam; }, /** * Abstract support for adding events uses: * http://ejohn.org/projects/flexible-javascript-events/ */ addEvent: function (obj, type, fn, useCapture) { if (obj.attachEvent) { obj['e' + type + fn] = fn; obj[type + fn] = function () { obj['e' + type + fn](window.event); } obj.attachEvent('on' + type, obj[type + fn]); } else { obj.addEventListener(type, fn, !!useCapture); } }, /** * Abstract support for removing events uses */ removeEvent: function (obj, type, fn) { if (obj.detachEvent) { obj.detachEvent('on' + type, obj[type + fn]); obj[type + fn] = null; } else { obj.removeEventListener(type, fn, false); } }, /** * Check if object is empty */ isEmptyObject: function (obj) { var name; for (name in obj) { return false; } return true; }, /** * Converts settings to url params * @param {object} settings Settings to be convert into url params */ embedSettingsToUrl: function (settings) { var url = ''; var kalturaAttributeList = ['uiconf_id', 'entry_id', 'wid', 'p', 'cache_st']; for (var attrKey in settings) { // Check if the attrKey is in the kalturaAttributeList: for (var i = 0; i < kalturaAttributeList.length; i++) { if (kalturaAttributeList[i] == attrKey) { url += '&' + attrKey + '=' + encodeURIComponent(settings[attrKey]); } } } // Add the flashvars: url += this.flashVarsToUrl(settings.flashvars); return url; }, /** * Overrides flash embed methods, as to optionally support HTML5 injection */ overrideFlashEmbedMethods: function () { var _this = this; var doEmbedSettingsWrite = function (settings, replaceTargetId, widthStr, heightStr) { if (widthStr) { settings.width = widthStr; } if (heightStr) { settings.height = heightStr; } kWidget.embed(replaceTargetId, settings); }; // flashobject if (window['flashembed'] && !window['originalFlashembed']) { window['originalFlashembed'] = window['flashembed']; window['flashembed'] = function (targetId, attributes, flashvars) { // TODO test with kWidget.embed replacement. _this.domReady(function () { var kEmbedSettings = kWidget.getEmbedSettings(attributes.src, flashvars); if (kEmbedSettings.uiconf_id && ( kWidget.isHTML5FallForward() || !kWidget.supportsFlash() )) { document.getElementById(targetId).innerHTML = '<div style="width:100%;height:100%" id="' + attributes.id + '"></div>'; doEmbedSettingsWrite(kEmbedSettings, attributes.id, attributes.width, attributes.height); } else { // Use the original flash player embed: return originalFlashembed(targetId, attributes, flashvars); } }); }; // add static methods var flashembedStaticMethods = ['asString', 'getHTML', 'getVersion', 'isSupported']; for (var i = 0; i < flashembedStaticMethods.length; i++) { window['flashembed'][ flashembedStaticMethods[i] ] = originalFlashembed } } // SWFObject v 1.5 if (window['SWFObject'] && !window['SWFObject'].prototype['originalWrite']) { window['SWFObject'].prototype['originalWrite'] = window['SWFObject'].prototype.write; window['SWFObject'].prototype['write'] = function (targetId) { var swfObj = this; // TODO test with kWidget.embed replacement. _this.domReady(function () { var kEmbedSettings = kWidget.getEmbedSettings(swfObj.attributes.swf, swfObj.params.flashVars); if (kEmbedSettings.uiconf_id && ( kWidget.isHTML5FallForward() || !kWidget.supportsFlash() )) { doEmbedSettingsWrite(kEmbedSettings, targetId, swfObj.attributes.width, swfObj.attributes.height); } else { // use the original flash player embed: swfObj.originalWrite(targetId); } }); }; } // SWFObject v 2.x if (window['swfobject'] && !window['swfobject']['originalEmbedSWF']) { window['swfobject']['originalEmbedSWF'] = window['swfobject']['embedSWF']; // Override embedObject for our own ends window['swfobject']['embedSWF'] = function (swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { // TODO test with kWidget.embed replacement. _this.domReady(function () { var kEmbedSettings = kWidget.getEmbedSettings(swfUrlStr, flashvarsObj); // Check if IsHTML5FallForward if (kEmbedSettings.uiconf_id && ( kWidget.isHTML5FallForward() || !kWidget.supportsFlash() )) { doEmbedSettingsWrite(kEmbedSettings, replaceElemIdStr, widthStr, heightStr); } else { // Else call the original EmbedSWF with all its arguments window['swfobject']['originalEmbedSWF'](swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn); } }); }; } } }; // Export to kWidget and KWidget ( official name is camel case kWidget ) window.KWidget = kWidget; window.kWidget = kWidget; })(window.jQuery);
kWidget/kWidget.js
/** * KWidget library provided embed layer services to html5 and flash players, as well as client side abstraction for some kaltura services. */ (function ($) { // Use strict ECMAScript 5 "use strict"; // Don't re-initialize kWidget if (window.kWidget) { return; } var kWidget = { //store the start time of the kwidget init startTime: {}, //store the load time of the player loadTime: {}, // Stores widgets that are ready: readyWidgets: {}, // stores original embed settings per widget: widgetOriginalSettings: {}, // First ready callback issued readyCallbacks: [], // List of widgets that have been destroyed destroyedWidgets: {}, // List per Widget callback, for clean destroy perWidgetCallback: {}, // Store the widget id ready callbacks in an array to avoid stacking on same id rewrite readyCallbackPerWidget: {}, listenerList: {}, // Stores per uiConf user agent rewrite rules userAgentPlayerRules: {}, // flag for the already added css rule: alreadyAddedThumbRules: false, // For storing iframe payloads via server side include, instead of an additional request // stored per player id iframeAutoEmbedCache: {}, // For storing iframe urls // Stored per player id iframeUrls: {}, /** * The master kWidget setup function setups up bindings for rewrites and * proxy of jsCallbackReady * * MUST BE CALLED AFTER all of the mwEmbedLoader.php includes. */ setup: function () { var _this = this; /** * set version: */ mw.setConfig('version', MWEMBED_VERSION); /** * Check the kWidget for environment settings and set appropriate flags */ this.checkEnvironment(); /** * Override flash methods, like swfObject, flashembed etc. * * NOTE for this override to work it your flash embed library must be included before mwEmbed */ this.overrideFlashEmbedMethods(); /** * Method call to proxy the jsCallbackReady * * We try to proxy both at include time and at domReady time */ this.proxyJsCallbackready(); this.domReady(function () { // set dom ready flag _this.domIsReady = true; _this.proxyJsCallbackready(); }); /** * Call the object tag rewrite, which will rewrite on-page object tags */ this.domReady(function () { _this.rewriteObjectTags(); }); }, /** * Checks the onPage environment context and sets appropriate flags. */ checkEnvironment: function () { // Note forceMobileHTML5 url flag be disabled by uiConf on the iframe side of the player // with: if ( document.URL.indexOf( 'forceMobileHTML5' ) !== -1 && !mw.getConfig( 'disableForceMobileHTML5' ) ) { mw.setConfig( 'forceMobileHTML5' , true ); } // Check for debugKalturaPlayer in url and set debug mode to true if ( document.URL.indexOf( 'debugKalturaPlayer' ) !== -1 ) { mw.setConfig( 'debug' , true ); } // Check for forceKPlayer in the URL if ( document.URL.indexOf( 'forceKPlayer' ) !== -1 ) { mw.setConfig( 'EmbedPlayer.ForceKPlayer' , true ); } var ua = navigator.userAgent; // Check if browser should use flash ( IE < 9 ) var ieMatch = document.documentMode ? ['', document.documentMode] : ua.match(/MSIE\s([0-9]+)/); if ( (ieMatch && parseInt( ieMatch[1] ) < 9) || document.URL.indexOf( 'forceFlash' ) !== -1 ) { mw.setConfig( 'Kaltura.ForceFlashOnDesktop' , true ); } // Blackberry does not really support html5 if ( ua.indexOf( 'BlackBerry' ) != -1 ) { mw.setConfig( 'EmbedPlayer.DisableVideoTagSupport' , true ); mw.setConfig( 'EmbedPlayer.NotPlayableDownloadLink' , true ); } if ( ua.indexOf( 'kalturaNativeCordovaPlayer' ) != -1 ) { mw.setConfig( 'EmbedPlayer.ForceNativeComponent' , true ); if ( !mw.getConfig( 'EmbedPlayer.IsIframeServer' ) ) { var cordovaPath; var cordovaKWidgetPath; if ( this.isAndroid() ) { cordovaPath = "/modules/EmbedPlayer/binPlayers/cordova/android/cordova.js"; } else { cordovaPath = "/modules/EmbedPlayer/binPlayers/cordova/ios/cordova.js"; } cordovaKWidgetPath = "/kWidget/cordova.kWidget.js"; document.write( '<script src="' + this.getPath() + cordovaPath + '"></scr' + 'ipt>' ); document.write( '<script src="' + this.getPath() + cordovaKWidgetPath + '"></scr' + 'ipt>' ); } } // iOS less than 5 does not play well with HLS: if ( /(iPhone|iPod|iPad)/i.test( ua ) ) { if ( /OS [2-4]_\d(_\d)? like Mac OS X/i.test( ua ) || (/CPU like Mac OS X/i.test( ua ) ) ) { mw.setConfig( 'Kaltura.UseAppleAdaptive' , false ); } } // Set iframe config if in the client page, will be passed to the iframe along with other config if ( !mw.getConfig( 'EmbedPlayer.IsIframeServer' ) ) { mw.setConfig( 'EmbedPlayer.IframeParentUrl' , document.URL ); mw.setConfig( 'EmbedPlayer.IframeParentTitle' , document.title ); mw.setConfig( 'EmbedPlayer.IframeParentReferrer' , document.referrer ); // Fix for iOS 5 not rendering iframe correctly when moving back/forward // http://stackoverflow.com/questions/7988967/problems-with-page-cache-in-ios-5-safari-when-navigating-back-unload-event-not if ( /(iPhone|iPod|iPad)/i.test( navigator.userAgent ) ) { if ( /OS [1-5](.*) like Mac OS X/i.test( navigator.userAgent ) ) { window.onpageshow = function ( evt ) { // If persisted then it is in the page cache, force a reload of the page. if ( evt.persisted ) { document.body.style.display = "none"; location.reload(); } }; } } } //Show non-production error by default, and allow overriding via flashvar if (!mw.getConfig( "Kaltura.SupressNonProductionUrlsWarning", false )) { // Check if using staging server on non-staging site: if ( // make sure this is Kaltura SaaS we are checking: mw.getConfig("Kaltura.ServiceUrl").indexOf('kaltura.com') != -1 && // check that the library is not on production this.getPath().indexOf('i.kaltura.com') == -1 && this.getPath().indexOf('isec.kaltura.com') == -1 && // check that we player is not on a staging site: window.location.host != 'kgit.html5video.org' && window.location.host != 'player.kaltura.com' && window.location.host != 'localhost' ) { if (console && console.error) { console.error("Error: Using non-production version of kaltura player library. Please see http://knowledge.kaltura.com/production-player-urls") } } } if (mw.getConfig( 'EmbedPlayer.ForceNativeComponent')) { // set up window.kNativeSdk window.kNativeSdk = window.kNativeSdk || {}; var typeMap = function(names) { if (typeof names !== 'string') { return []; } names = names.split(","); var mimeTypes = []; var map = { "dash": "application/dash+xml", "mp4": "video/mp4", "wvm": "video/wvm", "hls": "application/vnd.apple.mpegurl" }; for (var i = 0; i < names.length; i++) { mimeTypes.push(map[names[i]]); } return mimeTypes; }; // The Native SDK provides two lists of supported formats, after the hash sign. // Example: #nativeSdkDrmFormats=dash,wvm&nativeSdkAllFormats=dash,mp4,hls,wvm var drmFormats = kWidget.getHashParam("nativeSdkDrmFormats") || "wvm"; var allFormats = kWidget.getHashParam("nativeSdkAllFormats") || "wvm,mp4,hls"; window.kNativeSdk.drmFormats = typeMap(drmFormats); window.kNativeSdk.allFormats = typeMap(allFormats); } }, /** * Checks for the existence of jsReadyCallback and stores it locally. * all ready calls then are wrapped by the kWidget jsCallBackready function. */ proxiedJsCallback: null, waitForLibraryChecks: true, jsReadyCalledForIds: [], proxyJsCallbackready: function () { var _this = this; var jsCallbackProxy = function (widgetId) { // check if we need to wait. if (_this.waitForLibraryChecks) { // wait for library checks _this.jsReadyCalledForIds.push(widgetId); return; } // else we can call the jsReadyCallback directly: _this.jsCallbackReady(widgetId); }; // Always proxy js callback if (!this.proxiedJsCallback) { // Setup a proxied ready function: this.proxiedJsCallback = window['jsCallbackReady'] || true; // Override the actual jsCallbackReady window['jsCallbackReady'] = jsCallbackProxy } // secondary domready call check that jsCallbackReady was not overwritten: if (window['jsCallbackReady'].toString() != jsCallbackProxy.toString()) { this.proxiedJsCallback = window['jsCallbackReady']; // Override the actual jsCallbackReady with proxy window['jsCallbackReady'] = jsCallbackProxy } }, /** * The kWidget proxied jsCallbackReady * @param {string} widgetId The id of the widget that is ready */ jsCallbackReady: function (widgetId) { var _this = this; _this.log("jsCallbackReady for " + widgetId); if (this.destroyedWidgets[ widgetId ]) { // don't issue ready callbacks on destroyed widgets: return; } var player = document.getElementById(widgetId); if (!player || !player.evaluate) { this.callJsCallback(); this.log("Error:: jsCallbackReady called on invalid player Id:" + widgetId); return; } // extend the element with kBind kUnbind: this.extendJsListener(player); // check for inlineSciprts mode original settings: if( this.widgetOriginalSettings[widgetId] ){ // TODO these settings may be a bit late for plugins config ( should be set earlier in build out ) // for now just null out settings and changeMedia: player.kBind( 'kdpEmpty', function(){ player.sendNotification('changeMedia', {'entryId': _this.widgetOriginalSettings[widgetId].entry_id} ); } ); //player.sendNotification('changeMedia', {'entryId': this.widgetOriginalSettings[widgetId].entry_id} ); } var kdpVersion = player.evaluate('{playerStatusProxy.kdpVersion}'); //set the load time attribute supported in version kdp 3.7.x if (mw.versionIsAtLeast('v3.7.0', kdpVersion)) { _this.log("Error: Unsuported KDP version"); } else{ player.kBind('mediaReady', function () { // Set the load time against startTime for the current playerId: player.setKDPAttribute("playerStatusProxy", "loadTime", ( (new Date().getTime() - _this.startTime[ widgetId ] ) / 1000.0 ).toFixed(2) ); }); } // Support closing menu inside the player if (!mw.getConfig('EmbedPlayer.IsIframeServer')) { document.onclick = function () { //If player is destroyed don't send notification if (!_this.destroyedWidgets[ player.id ]) { player.sendNotification( 'onFocusOutOfIframe' ); } }; } // Check for proxied jsReadyCallback: if (typeof this.proxiedJsCallback == 'function') { this.proxiedJsCallback(widgetId); } this.callJsCallback(widgetId); }, callJsCallback: function (widgetId) { // Issue the callback for all readyCallbacks for (var i = 0; i < this.readyCallbacks.length; i++) { this.readyCallbacks[i](widgetId); } if (widgetId) { this.readyWidgets[ widgetId ] = true; } }, /** * Function to flag player mode checks. */ playerModeChecksDone: function () { // no need to wait for library checks any longer: this.waitForLibraryChecks = false; // Call any callbacks in the queue: for (var i = 0; i < this.jsReadyCalledForIds.length; i++) { var widgetId = this.jsReadyCalledForIds[i]; this.jsCallbackReady(widgetId); } // empty out the ready callback queue this.jsReadyCalledForIds = []; }, isDownloadLinkPlayer: function () { if (window.location.href.indexOf('forceDownloadPlayer') > -1 || mw.getConfig("EmbedPlayer.NotPlayableDownloadLink")) { return true; } return false; }, /** * The base embed method * @param targetId {String} Optional targetID string ( if not included, you must include in json) * @param settings {Object} Object of settings to be used in embedding. */ embed: function (targetId, settings) { if (this.isDownloadLinkPlayer()) { return this.thumbEmbed(targetId, settings, true); } var _this = this; // Supports passing settings object as the first parameter if (typeof targetId === 'object') { settings = targetId; if (!settings.targetId) { this.log('Error: Missing target element Id'); } targetId = settings.targetId; } // set player load check at start embed method call this.startTime[targetId] = new Date().getTime(); // Check if we have flashvars object if (!settings.flashvars) { settings.flashvars = {}; } if (this.isMobileDevice()){ if (settings.flashvars['layout']){ settings.flashvars.layout['skin'] = "kdark"; } } if ( document.URL.indexOf('forceKalturaNativeComponentPlayer') !== -1 || document.URL.indexOf('forceKalturaNative') !== -1) { settings.flashvars["nativeCallout"] = { plugin: true } } /** * Embed settings checks */ if (!settings.wid) { this.log("Error: kWidget.embed missing wid"); return; } var uiconf_id = settings.uiconf_id; var confFile = settings.flashvars.confFilePath ? settings.flashvars.confFilePath : settings.flashvars.jsonConfig; if (!uiconf_id && !confFile) { this.log("Error: kWidget.embed missing uiconf_id or confFile"); return; } // Make sure the replace target exists: var elm = document.getElementById(targetId); if (!elm) { this.log("Error: kWidget.embed could not find target: " + targetId); return false; // No target found ( probably already done ) } // Don't rewrite special key kaltura_player_iframe_no_rewrite if (elm.getAttribute('name') == 'kaltura_player_iframe_no_rewrite') { return; } // Check for "auto" localization and inject browser language. // We can't inject server side, because, we don't want to mangle the cached response // with params that are not in the request URL ( i.e AcceptLanguage headers ) if (settings.flashvars['localizationCode'] == 'auto') { var browserLangCode = window.navigator.userLanguage || window.navigator.language; // Just take the first part of the code ( not the country code ) settings.flashvars['localizationCode'] = browserLangCode.split('-')[0]; } // Empty the target ( don't keep SEO links on Page while loading iframe ) try { elm.innerHTML = ''; } catch (e) { // IE8 can't handle innerHTML on "read only" targets . } // Check for size override in kWidget embed call function checkSizeOverride(dim) { if (settings[ dim ]) { // check for non px value: if (parseInt(settings[ dim ]) == settings[ dim ]) { settings[ dim ] += 'px'; } elm.style[ dim ] = settings[ dim ]; } } checkSizeOverride('width'); checkSizeOverride('height'); // Unset any destroyed widget with the same id: if (this.destroyedWidgets[ targetId ]) { delete( this.destroyedWidgets[ targetId ] ); } // Check for ForceIframeEmbed flag if (mw.getConfig('Kaltura.ForceIframeEmbed') === true) { this.outputIframeWithoutApi(targetId, settings); return; } if (settings.readyCallback) { // only add a callback if we don't already have one for this id: var adCallback = !this.perWidgetCallback[ targetId ]; // add the per widget callback: this.perWidgetCallback[ targetId ] = settings.readyCallback; // Only add the ready callback for the current targetId being rewritten. if (adCallback) { this.addReadyCallback(function (videoId) { if (videoId == targetId && _this.perWidgetCallback[ videoId ]) { _this.perWidgetCallback[ videoId ](videoId); } }); } } // Be sure to jsCallbackready is proxied in dynamic embed call situations: this.proxyJsCallbackready(); settings.isHTML5 = this.isUiConfIdHTML5(uiconf_id); /** * Local scope doEmbed action, either writes out a msg, flash player */ var doEmbedAction = function () { // Evaluate per user agent rules for actions if (uiconf_id && _this.userAgentPlayerRules && _this.userAgentPlayerRules[ uiconf_id ]) { var playerAction = _this.checkUserAgentPlayerRules(_this.userAgentPlayerRules[ uiconf_id ]); // Default play mode, if here and really using flash re-map: switch (playerAction.mode) { case 'flash': if (elm.nodeName.toLowerCase() == 'object') { // do do anything if we are already trying to rewrite an object tag return; } break; case 'leadWithHTML5': settings.isHTML5 = _this.isUiConfIdHTML5(uiconf_id); break; case 'forceMsg': var msg = playerAction.val; // write out a message: if (elm && elm.parentNode) { var divTarget = document.createElement("div"); divTarget.style.backgroundColor = "#000000"; divTarget.style.color = "#a4a4a4"; divTarget.style.width = elm.style.width; divTarget.style.height = elm.style.height; divTarget.style.display = "table-cell"; divTarget.style.verticalAlign = "middle"; divTarget.style.textAlign = "center"; divTarget.style.fontSize = "1.5em"; divTarget.style.fontFamily = "Arial"; divTarget.style.fontWeight = "normal"; divTarget.innerHTML = unescape(msg); elm.parentNode.replaceChild(divTarget, elm); } return; break; } } // Check if we are dealing with an html5 native or flash player if (mw.getConfig("EmbedPlayer.ForceNativeComponent")) { _this.outputCordovaPlayer(targetId, settings); } else if (settings.isHTML5) { _this.outputHTML5Iframe(targetId, settings); } else { _this.outputFlashObject(targetId, settings); } } // load any onPage scripts if needed: // create a player list for missing uiconf check: var playerList = [ {'kEmbedSettings': settings } ]; // Load uiConfJS then call embed action this.loadUiConfJs(playerList, function () { // check that the proxy of js callback ready is up-to-date _this.proxyJsCallbackready(); doEmbedAction(); }); }, outputCordovaPlayer: function (targetId, settings) { var _this = this; if (cordova && cordova.kWidget) { cordova.kWidget.embed(targetId, settings); } else {//if cordova is not loaded run this function again after 500 ms setTimeout(function () { _this.outputCordovaPlayer(targetId, settings); }, 500) } }, addThumbCssRules: function () { if (this.alreadyAddedThumbRules) { return; } this.alreadyAddedThumbRules = true; var style = document.createElement('STYLE'); style.type = 'text/css'; var imagePath = this.getPath() + '/modules/MwEmbedSupport/skins/common/images/'; var cssText = '.kWidgetCentered {' + 'max-height: 100%; ' + 'max-width: 100%; ' + 'position: absolute; ' + 'top: 0; left: 0; right: 0; bottom: 0; ' + 'margin: auto; ' + '} ' + "\n" + '.kWidgetPlayBtn { ' + 'cursor:pointer;' + 'height: 53px;' + 'width: 70px;' + 'border-style: none;' + 'top: 50%; left: 50%; margin-top: -26.5px; margin-left: -35px; ' + 'background: url(\'' + imagePath + 'player_big_play_button.png\') ;' + 'z-index: 1;' + '} ' + "\n" + '.kWidgetAccessibilityLabel { ' + 'font-size:0;' + 'height: 1px;' + 'overflow: hidden;' + 'display:block;' + 'position:absolute;' + '} ' + "\n" + '.kWidgetPlayBtn:hover{ ' + 'background: url(\'' + imagePath + 'player_big_play_button_hover.png\');"' + '} '; if (this.isIE()) { style.styleSheet.cssText = cssText; } else { style.innerHTML = cssText; } // Append the style document.getElementsByTagName('HEAD')[0].appendChild(style); }, /** get the computed size of a target element */ getComputedSize: function (elm, dim) { var a = navigator.userAgent; if ((a.indexOf("msie") != -1) && (a.indexOf("opera") == -1 )) { return document.getElementById(theElt)[ 'offset' + dim[0].toUpperCase() + dim.substr(1) ]; } else { return parseInt(document.defaultView.getComputedStyle(elm, "").getPropertyValue(dim)); } }, /** * Used to do a light weight thumb embed player * the widget loaded anlytics event is triggered, * and a thumbReady callback is called * * All the other kWidget settings are invoked during playback. */ thumbEmbed: function (targetId, settings, forceDownload) { if (this.isDownloadLinkPlayer()) { forceDownload = true; } var _this = this; // Normalize the arguments if (typeof targetId === 'object') { settings = targetId; if (!settings.targetId) { this.log('Error: Missing target element Id'); } targetId = settings.targetId; } else { settings.targetId = targetId; } // Check if we have flashvars object if (!settings.flashvars) { settings.flashvars = {}; } // autoPlay media after thumbnail interaction settings.flashvars.autoPlay = true; // inject the centered css rule ( if not already ) this.addThumbCssRules(); // Add the width of the target to the settings: var elm = document.getElementById(targetId); if (!elm) { this.log("Error could not find target id, for thumbEmbed"); } elm.innerHTML = '' + '<div style="position: relative; width: 100%; height: 100%;">' + '<button aria-label="Play video content" class="kWidgetCentered kWidgetPlayBtn" ' + 'id="' + targetId + '_playBtn" ></button>' + '<img class="kWidgetCentered" src="' + this.getKalturaThumbUrl(settings) + '" alt="Video thumbnail">' + '</div>'; // Add a click binding to do the really embed: var playBtn = document.getElementById(targetId + '_playBtn'); this.addEvent(playBtn, 'click', function () { // Check for the ready callback: if (settings.readyCallback) { var orgEmbedCallback = settings.readyCallback; } settings.readyCallback = function (playerId) { // issue a play ( since we already clicked the play button ) var kdp = document.getElementById(playerId); kdp.kBind('mediaReady', function () { setTimeout(function () { if (_this.isMobileDevice()) { kdp.sendNotification('doPlay'); } }, 0); }); if (typeof orgEmbedCallback == 'function') { orgEmbedCallback(playerId); } } // Set a flag to capture the click event settings.captureClickEventForiOS = true; if (forceDownload) { window.open(_this.getDownloadLink(settings)); } else { // update the settings object kWidget.embed(settings); } }); // TOOD maybe a basic basic api ( doPlay support ? ) // thumb embed are ready as soon as they are embed: if (settings.thumbReadyCallback) { settings.thumbReadyCallback(targetId); } }, /** * Destroy a kWidget embed instance * * removes the target from the dom * * removes any associated * @param {Element|String} The target element or string to destroy */ destroy: function (target) { if (typeof target == 'string') { target = document.getElementById(target); } if (!target) { this.log("Error destory called without valid target"); return; } var targetId = target.id; var targetCss = target.style.cssText; var targetClass = target.className; var destoryId = target.getAttribute('id'); for (var id in this.readyWidgets) { if (id == destoryId) { delete( this.readyWidgets[ id ] ); } } this.destroyedWidgets[ destoryId ] = true; var newNode = document.createElement("div"); newNode.style.cssText = targetCss; newNode.id = targetId; newNode.className = targetClass; // remove the embed objects: target.parentNode.replaceChild(newNode, target); }, /** * Embeds the player from a set of on page objects with kEmbedSettings properties * @param {object} rewriteObjects set of in page object tags to be rewritten */ embedFromObjects: function (rewriteObjects) { for (var i = 0; i < rewriteObjects.length; i++) { var settings = rewriteObjects[i].kEmbedSettings; settings.width = rewriteObjects[i].width; settings.height = rewriteObjects[i].height; this.embed(rewriteObjects[i].id, rewriteObjects[i].kEmbedSettings); } }, /** * Extends the kWidget objects with (un)binding mechanism - kBind / kUnbind */ extendJsListener: function (player) { var _this = this; player.kBind = function (eventName, callback) { // Stores the index of anonymous callbacks for generating global functions var callbackIndex = 0; var globalCBName = ''; var _scope = this; // We can pass [eventName.namespace] as event name, we need it in order to remove listeners with their namespace if (typeof eventName == 'string') { var eventData = eventName.split('.', 2); var eventNamespace = ( eventData[1] ) ? eventData[1] : 'kWidget'; eventName = eventData[0]; } if (typeof callback == 'string') { globalCBName = callback; } else if (typeof callback == 'function') { // Make life easier for internal usage of the listener mapping by supporting // passing a callback by function ref var generateGlobalCBName = function () { globalCBName = 'kWidget_' + eventName + '_cb' + callbackIndex; if (window[ globalCBName ]) { callbackIndex++; generateGlobalCBName(); } }; generateGlobalCBName(); window[ globalCBName ] = function () { var args = Array.prototype.slice.call(arguments, 0); // move kbind into a timeout to restore javascript backtrace for errors, // instead of having flash directly call the callback breaking backtrace if (mw.getConfig('debug')) { setTimeout(function () { callback.apply(_scope, args); }, 0); } else { // note for production we directly issue the callback // this enables support for sync gesture rules for enterfullscreen. callback.apply(_scope, args); } }; } else { kWidget.log("Error: kWidget : bad callback type: " + callback); return; } // Storing a list of namespaces. Each namespace contains a list of eventnames and respective callbacks if (!_this.listenerList[ eventNamespace ]) { _this.listenerList[ eventNamespace ] = {} } if (!_this.listenerList[ eventNamespace ][ eventName ]) { _this.listenerList[ eventNamespace ][ eventName ] = globalCBName; } //kWidget.log( "kWidget :: kBind :: ( " + eventName + ", " + globalCBName + " )" ); player.addJsListener(eventName, globalCBName); return player; } player.kUnbind = function (eventName, callbackName) { //kWidget.log( "kWidget :: kUnbind :: ( " + eventName + ", " + callbackName + " )" ); if (typeof eventName == 'string') { var eventData = eventName.split('.', 2); var eventNamespace = eventData[1]; eventName = eventData[0]; // Remove event by namespace if (eventNamespace) { for (var listenerItem in _this.listenerList[ eventNamespace ]) { // Unbind the entire namespace if (!eventName) { player.removeJsListener(listenerItem, _this.listenerList[ eventNamespace ][ listenerItem ]); } // Only unbind the specified event within the namespace else { if (listenerItem == eventName) { player.removeJsListener(listenerItem, _this.listenerList[ eventNamespace ][ listenerItem ]); delete _this.listenerList[ eventNamespace ][ listenerItem ]; } } } _this.listenerList[ eventNamespace ] = null; } // No namespace was given else { var isCallback = ( typeof callbackName == 'string' ); // If a global callback name is given, then directly run removeJsListener if (isCallback) { player.removeJsListener(eventName, callbackName); } // If no callback was given, iterate over the list of listeners and remove all bindings per the given event name for (var eventNamespace in _this.listenerList) { for (var listenerItem in _this.listenerList[ eventNamespace ]) { if (listenerItem == eventName) { if (!isCallback) { player.removeJsListener(eventName, _this.listenerList[ eventNamespace ][ listenerItem ]); } delete _this.listenerList[ eventNamespace ][ listenerItem ]; } } } } } return player; } }, /** * Outputs a flash object into the page * * @param {string} targetId target container for iframe * @param {object} settings object used to build iframe settings */ outputFlashObject: function (targetId, settings, context) { context = context || document; var elm = context.getElementById(targetId); if (!elm && !elm.parentNode) { kWidget.log("Error embed target missing"); return; } // Only generate a swf source if not defined. if (!settings.src) { var swfUrl = mw.getConfig('Kaltura.ServiceUrl') + '/index.php/kwidget' + '/wid/' + settings.wid + '/uiconf_id/' + settings.uiconf_id; if (settings.entry_id) { swfUrl += '/entry_id/' + settings.entry_id; } if (settings.cache_st) { swfUrl += '/cache_st/' + settings.cache_st; } settings['src'] = swfUrl; } settings['id'] = elm.id; // update the container id: elm.setAttribute('id', elm.id + '_container'); // Output a normal flash object tag: var spanTarget = context.createElement("span"); // make sure flashvars are init: if (!settings.flashvars) { settings.flashvars = {}; } // Set our special callback flashvar: if (settings.flashvars['jsCallbackReadyFunc']) { kWidget.log("Error: Setting jsCallbackReadyFunc is not compatible with kWidget embed"); } // Check if in debug mode: if (mw.getConfig('debug', true)) { settings.flashvars['debug'] = true; } var flashvarValue = this.flashVarsToString(settings.flashvars); // we may have to borrow more from: // http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#407 // There seems to be issue with passing all the flashvars in playlist context. var defaultParamSet = { 'allowFullScreen': 'true', 'allowNetworking': 'all', 'allowScriptAccess': 'always', 'bgcolor': '#000000' }; // output css trim: var output = '<object style="' + elm.style.cssText.replace(/^\s+|\s+$/g, '') + ';display:block;" ' + ' class="' + elm.className + '" ' + ' id="' + targetId + '"' + ' name="' + targetId + '"'; output += ' data="' + settings['src'] + '" type="application/x-shockwave-flash"'; if (window.ActiveXObject) { output += ' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'; } output += '>'; output += '<param name="movie" value="' + settings['src'] + '" />'; output += '<param name="flashvars" value="' + flashvarValue + '" />'; // Output any custom params and let them override default params if (settings['params']) { for (var key in settings['params']) { if (defaultParamSet[key]) { defaultParamSet[key] = settings['params'][key]; } else { output += '<param name="' + key + '" value="' + settings['params'][key] + '" />'; } } } // output the default set of params for (var key in defaultParamSet) { if (defaultParamSet[key]) { output += '<param name="' + key + '" value="' + defaultParamSet[key] + '" />'; } } output += "</object>"; // Use local function to output contents to work around some browser bugs var outputElemnt = function () { // update the target: elm.parentNode.replaceChild(spanTarget, elm); spanTarget.innerHTML = output; } // XXX firefox with firebug enabled locks up the browser // detect firebug: if (window.console && ( window.console.firebug || window.console.exception )) { console.log('Warning firebug + firefox and dynamic flash kdp embed causes lockups in firefox' + ', ( delaying embed )'); this.domReady(function () { setTimeout(function () { outputElemnt(); }, 2000); }); } else { // IE needs to wait till dom ready if (navigator.userAgent.indexOf("MSIE") != -1) { setTimeout(function () { // MSIE fires DOM ready early sometimes outputElemnt(); }, 0); } else { outputElemnt(); } } }, createIframe: function(targetId, widgetElm){ var iframeId = widgetElm.id + '_ifp'; var iframeCssText = 'border:0px; max-width: 100%; max-height: 100%; width:100%;height:100%;'; var iframe = document.createElement("iframe"); iframe.id = iframeId; iframe.scrolling = "no"; iframe.name = iframeId; iframe.className = 'mwEmbedKalturaIframe'; iframe.setAttribute('title', 'The Kaltura Dynamic Video Player'); // IE8 requires frameborder attribute to hide frame border: iframe.setAttribute('frameborder', '0'); // Allow Fullscreen iframe.setAttribute('allowfullscreen', true); iframe.setAttribute('webkitallowfullscreen', true); iframe.setAttribute('mozallowfullscreen', true); // copy the target element css to the iframe proxy style: iframe.style.cssText = iframeCssText; // fix for iOS8 iframe overflow issue try { var iframeHeight = widgetElm.style.height ? widgetElm.style.height : widgetElm.offsetHeight; if (this.isIOS() && (parseInt(iframeHeight) > 0)) { iframe.style.height = iframeHeight; var updateIframeID = setTimeout(function(){ iframe.style.height = "100%"; },6000); window.addEventListener("message", function(event){ if ( event.data === 'layoutBuildDone' ){ iframe.style.height = "100%"; clearTimeout(updateIframeID); } }, false); } } catch (e) { this.log("Error when trying to set iframe height: " + e.message); } return iframe; }, createIframeProxy: function(widgetElm){ var iframeProxy = document.createElement("div"); iframeProxy.id = widgetElm.id; iframeProxy.name = widgetElm.name; var moreClass = widgetElm.className ? ' ' + widgetElm.className : ''; iframeProxy.className = 'kWidgetIframeContainer' + moreClass; // Update the iframe proxy style per org embed widget: iframeProxy.style.cssText = widgetElm.style.cssText + ';overflow: hidden'; return iframeProxy; }, createContentInjectCallback: function(cbName, iframe, iframeRequest, settings, ttlUnixVal){ var _this = this; // Do a normal async content inject: window[ cbName ] = function ( iframeData ) { var newDoc = iframe.contentWindow.document; if(_this.isFirefox()){ // in FF we have to pass the "replace" parameter to inherit the current history newDoc.open("text/html", "replace"); } else { newDoc.open(); } newDoc.write(iframeData.content); // TODO are we sure this needs to be on this side of the iframe? if ( mw.getConfig("EmbedPlayer.DisableContextMenu") ){ newDoc.getElementsByTagName('body')[0].setAttribute("oncontextmenu","return false;"); } newDoc.close(); if( _this.isInlineScriptRequest(settings) && kWidget.storage.isSupported()){ // if empty populate for the first time: var iframeStoredData = kWidget.storage.getWithTTL( iframeRequest ); if (iframeStoredData == null) { _this.cachePlayer(iframeRequest, iframeData.content, ttlUnixVal); } } // Clear out this global function window[cbName] = null; }; }, createContentUpdateCallback: function(cbName, iframeRequest, settings, ttlUnixVal, maxCacheEntries){ var _this = this; window[cbName] = function (iframeData) { // only populate the cache if request was an inlines scripts request. if (_this.isInlineScriptRequest(settings) && kWidget.storage.isSupported()) { _this.cachePlayer(iframeRequest, iframeData.content, ttlUnixVal); } // Clear out this global function window[cbName] = null; }; }, requestPlayer: function(iframeRequest, widgetElm, targetId, cbName, settings){ var _this = this; if ( iframeRequest.length > 2083 ){ //TODO:Need to output an error, cause we don't depend on jquery explicitly this.log( "Warning iframe requests (" + iframeRequest.length + ") exceeds 2083 charachters, won't cache on CDN." ); var url = this.getIframeUrl(); var requestData = iframeRequest; var isLowIE = document.documentMode && document.documentMode < 10; if ( isLowIE && settings.flashvars.jsonConfig ){ // -----> IE8 and IE9 hack to solve Studio issues. SUP-3795. Should be handled from PHP side and removed <---- jsonConfig = settings.flashvars.jsonConfig; delete settings.flashvars.jsonConfig; url += '?' + this.getIframeRequest(widgetElm, settings); requestData = {"jsonConfig": jsonConfig}; url += "&protocol=" + location.protocol.slice(0, -1); } else { url += "?protocol=" + location.protocol.slice(0, -1); } $.ajax({ type: "POST", dataType: 'text', url: url, data: requestData }) .success(function (data) { var contentData = {content: data}; window[cbName](contentData); }) .error(function (e) { _this.log("Error in player iframe request") }) } else { var iframeUrl = this.getIframeUrl() + '?' + iframeRequest; iframeUrl += "&protocol=" + location.protocol.slice(0, -1); // Store iframe urls this.iframeUrls[ targetId ] = iframeUrl; // do an iframe payload request: this.appendScriptUrl( iframeUrl +'&callback=' + cbName ); } }, isStorageMaxLimitExceeded: function(settings){ //Get max cache entries form user settings or use default var maxCacheEntries = settings.flashvars["Kaltura.MaxCacheEntries"]|| mw.getConfig("Kaltura.MaxCacheEntries"); var cacheEntriesCount = kWidget.storage.getEntriesCount(); return (cacheEntriesCount >= maxCacheEntries); }, cachePlayer: function(key, value, ttl){ var success = kWidget.storage.setWithTTL(key, value, ttl); if (success) { this.log("Player data stored in cache!"); } else { this.log("Error: unable to store Player data in cache!"); } }, /** * Output an html5 iframe player, once the html5 library is loaded * * @param {string} targetId target container for iframe * @param {object} settings object used to build iframe settings */ outputHTML5Iframe: function (targetId, settings) { var widgetElm = document.getElementById(targetId); var iframe = this.createIframe(targetId, widgetElm); // Create the iframe proxy that wraps the actual iframe // and will be converted into an "iframe" player via jQuery.fn.iFramePlayer call var iframeProxy = this.createIframeProxy(widgetElm); iframeProxy.appendChild(iframe); // Replace the player with the iframe: widgetElm.parentNode.replaceChild(iframeProxy, widgetElm); var requestSettings = JSON.parse(JSON.stringify(settings)); // Check if its a inline scripts setup: if( this.isInlineScriptRequest( requestSettings ) ){ // segment out all configuration requestSettings = this.getRuntimeSettings( requestSettings ); this.widgetOriginalSettings [widgetElm.id] = settings; mw.setConfig("widgetOriginalSettings_" + widgetElm.id, settings); } else { //If this is not an inlineScript request or we don't support it make sure to falsify it settings.flashvars['inlineScript'] = false; } // Check if we need to capture a play event ( iOS sync embed call ) if (settings.captureClickEventForiOS && (this.isIOS() || this.isAndroid())) { this.captureClickWrapedIframeUpdate(targetId, requestSettings, iframe); } else { // get the callback name: var cbName = this.getIframeCbName(targetId); var iframeRequest = this.getIframeRequest(widgetElm, requestSettings); //Get TTL for cache entries form user settings or use default var ttlUnixVal = settings.flashvars["Kaltura.CacheTTL"] || mw.getConfig("Kaltura.CacheTTL"); //Prepare an iframe content injection hook this.createContentInjectCallback(cbName, iframe, iframeRequest, requestSettings, ttlUnixVal); // Try and get playload from local cache ( autoEmbed ) if (this.iframeAutoEmbedCache[targetId]) { window[cbName](this.iframeAutoEmbedCache[targetId]); } else { // try to get payload from localStorage cache var iframeData = null; if (kWidget.storage.isSupported()) { iframeData = kWidget.storage.getWithTTL(iframeRequest); } //If iframe content is in cache then load it immediately and update from server for next time if (!mw.getConfig('debug') && iframeData && iframeData != "null") { window[cbName]({'content': iframeData}); // we don't retrun here, instead we run the get request to update the uiconf storage // TODO this should just be a 304 check not a full download of the iframe ( normally ) // RETURN UNTIL WE HAVE 30$ check in palce. //return ; cbName += "updateAsync"; // after loading iframe, prepare a content update hook this.createContentUpdateCallback(cbName, iframeRequest, requestSettings, ttlUnixVal); } //Enforce the max storage entries setting to avoid over populating the localStorage if (kWidget.storage.isSupported() && this.isStorageMaxLimitExceeded(settings)) { kWidget.storage.clearNS(); } // Do a normal async content inject/update request: this.requestPlayer(iframeRequest, widgetElm, targetId, cbName, requestSettings); } } }, /** * Returns the callback name for an iframe */ getIframeCbName: function (iframeId) { var _this = this; var inx = 0; var baseCbName = 'mwi_' + iframeId.replace(/[^0-9a-zA-Z]/g, ''); var cbName = baseCbName + inx; while (window[ cbName ]) { _this.log("Warning: iframe callback already defined: " + cbName); inx++; cbName = baseCbName + inx; } return cbName; }, // TODO does this need to be part of the kWidget library? resizeOvelayByHolderSize: function (overlaySize, parentSize, ratio) { var overlayRatio = overlaySize.width / overlaySize.height; var centeredParent = { 'width' : parentSize.width * ratio, 'height' : parentSize.height * ratio }; var diffs = { 'width' : parentSize.width - overlaySize.width, 'height' : parentSize.height - overlaySize.height }; var screenSize = { 'width' : 0, 'height' : 0 }; // Image size smaller then then the videoHolder size if (diffs.width > 0 && diffs.height > 0) { screenSize.width = overlaySize.width; screenSize.height = overlaySize.height; // Image height bigger or equals to video holder height and image width is smaller } else if (diffs.width > 0 && diffs.height <= 0) { screenSize.height = centeredParent.height; screenSize.width = screenSize.height * overlayRatio; // Image width bigger or equals to video holder width and image height is smaller } else if (diffs.width <= 0 && diffs.height > 0) { screenSize.width = centeredParent.width; screenSize.height = screenSize.width / overlayRatio; // Image size bigger then video holder size } else if (diffs.width <= 0 && diffs.height <=0) { // Check which value is bigger to use the biggest ratio if (diffs.width <= diffs.height) { screenSize.width = centeredParent.width; screenSize.height = screenSize.width / overlayRatio; } else { screenSize.height = centeredParent.height; screenSize.width = screenSize.height * overlayRatio; } } return screenSize; }, /** * Supports the iOS captured clicks iframe update, * * Inserts a video tag synchronously into the iframe, ( pointed to black video file ) * Issues play on the iframe video tag * Issues async request to grab iframe data with "no video tag" * Runs script blocks and allows iframe to update persistent video tag. * * @param {String} targetId The target id to be updated * @param {Object} settings The embed Settings object * @param {Element} iframeElm The target iframe element the page. */ captureClickWrapedIframeUpdate: function (targetId, settings, iframeElm) { var _this = this; var widgetElm = document.getElementById(targetId); var newDoc = iframeElm.contentDocument; newDoc.open(); // grab a black source var vidSrc = location.protocol + '//www.kaltura.com/p/243342/sp/24334200/playManifest/entryId/1_vp5cng42/flavorId/1_6wf0o9n7/format/url/protocol/http/a.mp4'; // Add the iframe skeleton with video element to the iframe newDoc.write('<html>' + '<head></head>' + '<body>' + '<div class="mwPlayerContainer" style="width: 100%; height: 100%">' + '<div class="videoHolder">' + '<video class="persistentNativePlayer" ' + 'id="' + targetId + '" ' + 'kwidgetid="' + settings.wid + '" ' + 'kentryid="' + settings.entry_id + '" ' + 'kuiconfid="' + settings.uiconf_id + '" ' + //'poster="' + _this.getKalturaThumbUrl( settings ) + '" ' + // Only applies to iOS, and only to caputre the play event, // so we only include a low bitrate mp4 'src="' + vidSrc + '" ' + 'style="width:100%;height:100%" ' + '>' + '</video>' + '</div>' + '</div>' + // issue play on the silent black video ( to capture iOS gesture ) '<scr'+'ipt>document.getElementById(\'' + targetId + '\').play();</scr'+'ipt>' + '<div id="scriptsHolder"></div>' + '</body>' + '</html>' ); newDoc.close(); // get the callback name: var cbName = this.getIframeCbName(targetId); // Else do a normal async include: window[ cbName ] = function (iframeParts) { // update the header: var head = iframeElm.contentDocument.getElementsByTagName("head")[0] || iframeElm.documentElement; head.innerHTML = iframeParts.rawHead; // append the scripts: iframeElm.contentDocument.getElementById("scriptsHolder").innerHTML = iframeParts.rawScripts; var nodeName = function (elem, name) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); } // eval a script in the iframe context var evalScript = function (elem) { var data = ( elem.text || elem.textContent || elem.innerHTML || "" ); var head = iframeElm.contentDocument.getElementsByTagName("head")[0] || iframeElm.documentElement; var script = iframeElm.contentDocument.createElement("script"); script.type = "text/javascript"; script.appendChild(document.createTextNode(data)); head.insertBefore(script, head.firstChild); //head.removeChild( script ); if (elem.parentNode) { elem.parentNode.removeChild(elem); } } var scripts = []; var headElm = head.childNodes; //var ret = iframeElm.contentDocument.body.childNodes; var ret = iframeElm.contentDocument.getElementById("scriptsHolder").childNodes; for (var i = 0; ret[i]; i++) { if (scripts && nodeName(ret[i], "script") && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript")) { scripts.push(ret[i].parentNode ? ret[i].parentNode.removeChild(ret[i]) : ret[i]); } } // eval all the raw scripts for (var script in scripts) { evalScript(scripts[ script ]); } }; // Add the iframe script: _this.appendScriptUrl(this.getIframeUrl() + '?' + this.getIframeRequest(widgetElm, settings) + '&callback=' + cbName + '&parts=1'); }, isInlineScriptRequest: function( settings ){ // don't inline scripts in debug mode: if( mw.getConfig('debug') || this.isMobileDevice()){ return false; } // check for inlineScript flag: if( settings.flashvars['inlineScript'] ){ return true; } return false; }, // retruns only the runtime config getRuntimeSettings: function( settings ){ var runtimeSettings = {}; var allowedVars = mw.getConfig('Kaltura.AllowedVars'); allowedVars = allowedVars.split(","); var allowedVarsKeyPartials = mw.getConfig('Kaltura.AllowedVarsKeyPartials'); allowedVarsKeyPartials = allowedVarsKeyPartials.split(","); var allowedPluginVars = mw.getConfig('Kaltura.AllowedPluginVars'); allowedPluginVars = allowedPluginVars.split(","); var allowedPluginVarsValPartials = mw.getConfig('Kaltura.AllowedPluginVarsValPartials'); allowedPluginVarsValPartials = allowedPluginVarsValPartials.split(","); for( var settingsKey in settings ){ // entry id should never be included ( hurts player iframe cache ) if( settingsKey == 'entry_id' ){ continue; } if( settingsKey =='flashvars' ){ // add flashvars container: var runtimeFlashvars = runtimeSettings[settingsKey] = {}; var flashvars = settings[settingsKey]; for( var flashvarKey in flashvars ){ if( typeof flashvars[flashvarKey] != 'object' ) { var flashvar = flashvars[flashvarKey]; // Special Case a few flashvars that are always copied to iframe: if ([].indexOf.call(allowedVars, flashvarKey, 0) > -1) { runtimeFlashvars[flashvarKey] = flashvar; continue; } // Special case vars that require server side template substations for (var idx in allowedVarsKeyPartials) { if (flashvarKey.indexOf(allowedVarsKeyPartials[idx]) > -1) { runtimeFlashvars[flashvarKey] = flashvar; continue; } } } if( typeof flashvars[flashvarKey] == 'object' ){ // Set an empty plugin if any value is preset ( note this means .plugin=false overrides do still load the plugin // but this is "OK" because the client is likely setting this at runtime on purpose. Its more value // to get a cache hit all time time independently of alerting enabled/disabled flag. // Plugin diablement will still be read during runtime player build-out. var runtimePlugin = runtimeFlashvars[flashvarKey]={}; var plugin = flashvars[flashvarKey]; for( var pluginKey in plugin ) { var pluginVal = plugin[pluginKey]; // Special Case a few flashvars that are always copied to iframe: if ([].indexOf.call( allowedPluginVars, pluginKey, 0 ) > -1) { runtimePlugin[pluginKey] = pluginVal; continue; } if (typeof pluginVal == "string") { // Special case vars that require server side template substations for (var idx in allowedPluginVarsValPartials) { if (pluginVal.indexOf(allowedPluginVarsValPartials[idx]) > -1){ runtimePlugin[pluginKey] = plugin[pluginKey]; continue; } } } } } } // don't do high level copy of flashvars continue; } runtimeSettings[ settingsKey ] = settings[settingsKey]; } return runtimeSettings; }, /** * Build the iframe request from supplied settings: */ getIframeRequest: function (elm, settings) { // Get the base set of kaltura params ( entry_id, uiconf_id etc ) var iframeRequest = this.embedSettingsToUrl( settings ); // Add the player id: iframeRequest += '&playerId=' + elm.id; // Add &debug is in debug mode if (mw.getConfig('debug')) { iframeRequest += '&debug=true'; } // add ps if set: if (mw.getConfig('Kaltura.KWidgetPsPath')) { iframeRequest += '&pskwidgetpath=' + mw.getConfig('Kaltura.KWidgetPsPath'); } // If remote service is enabled pass along service arguments: if (mw.getConfig('Kaltura.AllowIframeRemoteService') && ( mw.getConfig("Kaltura.ServiceUrl").indexOf('kaltura.com') === -1 && mw.getConfig("Kaltura.ServiceUrl").indexOf('kaltura.org') === -1 ) ) { iframeRequest += kWidget.serviceConfigToUrl(); } // Add no cache flag if set: if (mw.getConfig('Kaltura.NoApiCache')) { iframeRequest += '&nocache=true'; } if (this.isUiConfIdHTML5(settings.uiconf_id)) { iframeRequest += '&forceMobileHTML5=true'; } // Also append the script version to purge the cdn cache for iframe: iframeRequest += '&urid=' + MWEMBED_VERSION; return iframeRequest; }, getIframeUrl: function () { var path = this.getPath(); if (mw.getConfig('Kaltura.ForceIframeEmbed') === true) { // In order to simulate iframe embed we need to use different host path = path.replace('localhost', '127.0.0.1'); } return path + 'mwEmbedFrame.php'; }, getPath: function () { return SCRIPT_LOADER_URL.replace('load.php', ''); }, /** * Output an iframe without api. ( should rarely be used, this disable on page javascript api, * as well as native fullscreen on browsers that support it. * * @param {string} replaceTargetId target container for iframe * @param {object} kEmbedSettings object used to build iframe settings */ outputIframeWithoutApi: function (targetId, settings) { var targetEl = document.getElementById(targetId); var iframeSrc = this.getIframeUrl() + '?' + this.getIframeRequest(targetEl, settings) + '&iframeembed=true'; var targetNode = document.getElementById(targetId); var parentNode = targetNode.parentNode; var iframe = document.createElement('iframe'); iframe.src = iframeSrc; iframe.id = targetId; iframe.width = (settings.width) ? settings.width.replace(/px/, '') : '100%'; iframe.height = (settings.height) ? settings.height.replace(/px/, '') : '100%'; iframe.className = targetNode.className ? ' ' + targetNode.className : ''; // Update the iframe proxy style per org embed widget: iframe.style.cssText = targetNode.style.cssText; iframe.style.border = '0px'; iframe.style.overflow = 'hidden'; parentNode.replaceChild(iframe, targetNode); }, /** * Adds a ready callback to be called once the kdp or html5 player is ready * @param {function} readyCallback called once a player or widget is ready on the page */ addReadyCallback: function (readyCallback) { // Issue the ready callback for any existing ready widgets: for (var widgetId in this.readyWidgets) { // Make sure the widget is not already ready and is still in the dom: if (document.getElementById(widgetId)) { readyCallback(widgetId); } } // Add the callback to the readyCallbacks array for any other players that become ready this.readyCallbacks.push(readyCallback); // Make sure we proxy the ready callback: this.proxyJsCallbackready(); }, /** * Search the DOM for Object tags and rewrite them if they should be rewritten. * * rewrite rules include: * - userAgentRules -- may result in loading uiConf rewrite rules * - forceMobileHTML5 -- a url flag to force HTML5 for testing, can be disabled on iframe side, * per uiConf vars * - ForceFlashOnDesktop -- forces flash for desktop browsers. */ rewriteObjectTags: function () { // get the list of object tags to be rewritten: var playerList = this.getKalutaObjectList(); var _this = this; // don't bother with checks if no players exist: if (!playerList.length) { this.playerModeChecksDone(); return; } // Check if we need to load UiConf JS if (this.isMissingUiConfJs(playerList)) { // Load uiConfJS then re call the rewriteObjectTags method: this.loadUiConfJs(playerList, function () { _this.rewriteObjectTags(); }) return; } /** * If Kaltura.AllowIframeRemoteService is not enabled force in page rewrite: */ var serviceUrl = mw.getConfig('Kaltura.ServiceUrl'); if (!mw.getConfig('Kaltura.AllowIframeRemoteService')) { if (!serviceUrl || serviceUrl.indexOf('kaltura.com') === -1) { // if not hosted on kaltura for now we can't use the iframe to load the player mw.setConfig('Kaltura.IframeRewrite', false); mw.setConfig('Kaltura.UseManifestUrls', false); } } /* * TODO revisit support for video tag rewrites ( maybe redirect to iframe style embed ) if( ! mw.getConfig( 'Kaltura.ForceFlashOnDesktop' ) && ( mw.getConfig( 'Kaltura.LoadScriptForVideoTags' ) && this.pageHasAudioOrVideoTags() ) ){ loadHTML5LibAndRewriteTags(); return ; } */ // check for global lead with html5: if (this.isHTML5FallForward()) { this.embedFromObjects(playerList); return; } // loop over the playerList check if given uiConf should be lead with html: for (var i = 0; i < playerList.length; i++) { if (this.isUiConfIdHTML5(playerList[i].kEmbedSettings['uiconf_id'])) { this.embedFromObjects([ playerList[i] ]); } } // Check if no flash and no html5 and no forceFlash ( direct download link ) if (!this.supportsFlash() && !this.supportsHTML5() && !mw.getConfig('Kaltura.ForceFlashOnDesktop')) { this.embedFromObjects(playerList); return; } this.playerModeChecksDone(); }, // Global instance of uiConf ids and associated script loaded state uiConfScriptLoadList: {}, /** * Stores a callback for inLoadJs ( replaced by direct callback if that is all the players we are worried about ) */ // flag for done loading uiConfJs inLoaderUiConfJsDone: false, inLoaderUiConfJsCallbackSet: [], inLoaderUiConfJsCallback: function () { this.inLoaderUiConfJsDone = true; while (this.inLoaderUiConfJsCallbackSet.length) { this.inLoaderUiConfJsCallbackSet.shift()(); } }, /** * Check if any player is missing uiConf javascript: * @param {object} playerList List of players to check for missing uiConf js */ isMissingUiConfJs: function (playerList) { // Check if we are waiting for inLoader uiconf js: if (this.inLoaderUiConfJsDone == false) { return true; } // Check if we need to load uiConfJs ( for non-inLoaderUiConfJs ) if (playerList.length == 0 || !mw.getConfig('Kaltura.EnableEmbedUiConfJs') || mw.getConfig('EmbedPlayer.IsIframeServer')) { return false; } for (var i = 0; i < playerList.length; i++) { var settings = playerList[i].kEmbedSettings; if (!this.uiConfScriptLoadList[ settings.uiconf_id ]) { return true; } } return false; }, uiConfScriptLoadListCallbacks: {}, /** * Loads the uiConf js for a given playerList * @param {object} playerList list of players to check for uiConf js * @param {function} callback, called once all uiConf service calls have been made */ loadUiConfJs: function (playerList, doneCallback) { var _this = this; // Check if we cover all uiConfs via inLoaderUiConfJs var callback = function () { // check if the done flag has been set: if (_this.inLoaderUiConfJsDone) { doneCallback() } else { // replace the callback _this.inLoaderUiConfJsCallbackSet.push(doneCallback); } return; } // We have not yet loaded uiConfJS... load it for each ui_conf id var baseUiConfJsUrl = this.getPath() + 'services.php?service=uiconfJs'; // add ps if set: if (mw.getConfig('Kaltura.KWidgetPsPath')) { baseUiConfJsUrl += '&pskwidgetpath=' + mw.getConfig('Kaltura.KWidgetPsPath'); } if (!this.isMissingUiConfJs(playerList)) { // called with empty request set: callback(); return; } var foundPlayerMissingUiConfJs = false; for (var i = 0; i < playerList.length; i++) { // Create a local scope for the current uiconf_id: (function (settings) { if (_this.uiConfScriptLoadList[ settings.uiconf_id ]) { // player ui conf js is already loaded skip: return; } foundPlayerMissingUiConfJs = true; // Setup uiConf callback so we don't risk out of order execution var cbName = 'kUiConfJs_' + i + '_' + settings.uiconf_id; if (!_this.uiConfScriptLoadListCallbacks[ cbName ]) { _this.uiConfScriptLoadListCallbacks[ cbName ] = [ callback ]; window[ cbName ] = function () { _this.uiConfScriptLoadList[ settings.uiconf_id ] = true; // issue all uiConfScriptLoad callbacks: for (var inx in _this.uiConfScriptLoadListCallbacks[ cbName ]) { if (_this.uiConfScriptLoadListCallbacks[ cbName ].hasOwnProperty(inx) && typeof _this.uiConfScriptLoadListCallbacks[ cbName ][inx] == 'function') { _this.uiConfScriptLoadListCallbacks[ cbName ][inx](); } } ; }; // add the services.php includes: var scriptUrl = baseUiConfJsUrl + _this.embedSettingsToUrl(settings) + '&callback=' + cbName; if (scriptUrl.length > 4096){ _this.log( "Warning iframe requests (" + scriptUrl.length + ") exceeds 4096 characters, won't cache on CDN." ) $.ajax({ type: "POST", dataType: 'text', url: _this.getIframeUrl(), data: _this.embedSettingsToUrl(settings) }).success(function (data) { var contentData = {content: data}; window[cbName](contentData); }) .error(function (e) { _this.log("Error in player iframe request"); }); }else{ _this.appendScriptUrl(scriptUrl); } } else { // add the callback _this.uiConfScriptLoadListCallbacks[ cbName ].push(callback); } })(playerList[i].kEmbedSettings); } // check if we should wait for a player to load its uiConf: if (!foundPlayerMissingUiConfJs) { callback(); return; } }, /** * Write log message to the console * TODO support log levels: https://github.com/kaltura/mwEmbed/issues/80 */ log: function (msg) { // only log if debug is active: if (typeof mw != 'undefined' && !mw.getConfig('debug')) { return; } if (typeof console != 'undefined' && console.log) { if (this.isIE8()){ try{ console.log("kWidget: " + msg); }catch(e){} }else{ console.log("kWidget: " + msg); } } }, /** * If the current player supports html5: * @return {boolean} true or false if HTML5 video tag is supported */ supportsHTML5: function () { if (mw.getConfig('EmbedPlayer.DisableVideoTagSupport')) { return false; } var dummyvid = document.createElement("video"); if (dummyvid.canPlayType) { return true; } return false; }, supportsHTMLPlayerUI: function () { return this.supportsHTML5() || (this.isIE8() && this.supportsFlash()); }, /** * If the browser supports flash * @return {boolean} true or false if flash > 10 is supported. */ supportsFlash: function () { if (mw.getConfig('EmbedPlayer.DisableHTML5FlashFallback')) { return false; } var version = this.getFlashVersion().split(',').shift(); if (version < 10) { return false; } else { return true; } }, /** * Checks for flash version * @return {string} flash version string */ getFlashVersion: function () { // navigator browsers: if (navigator.plugins && navigator.plugins.length) { try { if (navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) { return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1]; } } catch (e) { } } // IE try { try { if (typeof ActiveXObject != 'undefined') { // avoid fp6 minor version lookup issues // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/ var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6'); try { axo.AllowScriptAccess = 'always'; } catch (e) { return '6,0,0'; } } } catch (e) { } return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } catch (e) { } return '0,0,0'; }, /** * Checks for iOS devices **/ isIOS: function () { return ( (navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1) ); }, isFirefox: function(){ return navigator.userAgent.indexOf('Firefox') != -1; }, isIE: function () { return /\bMSIE\b/.test(navigator.userAgent); }, isIE8: function () { return document.documentMode === 8; }, isAndroid: function () { return (navigator.userAgent.indexOf('Android ') !== -1 && navigator.userAgent.indexOf('Windows') === -1); }, isWindowsDevice: function () { var appVer = navigator.appVersion; return ((appVer.indexOf("Win") != -1 && (navigator.appVersion.indexOf("Phone") != -1 || navigator.appVersion.indexOf("CE") != -1))); }, /** * Checks for mobile devices **/ isMobileDevice: function () { return (this.isIOS() || this.isAndroid() || this.isWindowsDevice() || mw.getConfig("EmbedPlayer.ForceNativeComponent") || mw.getConfig("EmbedPlayer.SimulateMobile") === true ); }, isChromeCast: function(){ return (/CrKey/.test(navigator.userAgent)); }, /** * Checks if a given uiconf_id is html5 or not * @param {string} uiconf_id The uiconf id to check against user player agent rules */ isUiConfIdHTML5: function (uiconf_id) { var isHTML5 = this.isHTML5FallForward(); if (this.userAgentPlayerRules && this.userAgentPlayerRules[ uiconf_id ]) { var playerAction = this.checkUserAgentPlayerRules(this.userAgentPlayerRules[ uiconf_id ]); if (playerAction.mode == 'leadWithHTML5') { isHTML5 = this.supportsHTMLPlayerUI(); } } return isHTML5; }, /** * Fallforward by default prefers flash, uses html5 only if flash is not installed or not available */ isHTML5FallForward: function () { // Check for a mobile html5 user agent: if (this.isIOS() || mw.getConfig('forceMobileHTML5')) { return true; } // Check for "Kaltura.LeadWithHTML5" attribute // Only return true if the browser actually supports html5 if ( ( mw.getConfig('KalturaSupport.LeadWithHTML5') || mw.getConfig('Kaltura.LeadWithHTML5') ) && this.supportsHTMLPlayerUI() ) { return true; } // Special check for Android: if (this.isAndroid()) { if (mw.getConfig('EmbedPlayer.UseFlashOnAndroid') && kWidget.supportsFlash() ) { // Use flash on Android if available return false; } else { // Some Android supports the video tag return true; } } /** * If the browser supports flash ( don't use html5 ) * On ModernUI IE10, Flash is integrated. However, our Flash detection on IE looks for ActiveX which is disabled, thus failing. */ if (kWidget.supportsFlash()) { return false; } /** * Allow forcing flash on IE10 * Since we don't check Microsoft's CV list, we cannot say whether a domain has been whitelisted for Flash or not. * Due to that, we fallback to HTML5 player on Modern UI IE10 by default * Using this flag this can be overriden. */ if (mw.getConfig('Kaltura.ForceFlashOnIE10')) { var ua = navigator.userAgent; var ie10Match = document.documentMode === 10; if (ie10Match) { return false; } } // Check if the UseFlashOnDesktop flag is set and ( don't check for html5 ) if (mw.getConfig('Kaltura.ForceFlashOnDesktop')) { return false; } // No flash return true if the browser supports html5 video tag with basic support for canPlayType: if (kWidget.supportsHTML5()) { return true; } // if we have the iframe enabled return true ( since the iframe will output a fallback link // even if the client does not support html5 or flash ) if (mw.getConfig('Kaltura.IframeRewrite')) { return true; } // No video tag or flash, or iframe, normal "install flash" user flow ) return false; }, getDownloadLink: function (settings) { var _this = this; // update the settings object var baseUrl = _this.getPath(); var downloadUrl = baseUrl + 'modules/KalturaSupport/download.php/wid/' + settings.wid; // Also add the uiconf id to the url: if (settings.uiconf_id) { downloadUrl += '/uiconf_id/' + settings.uiconf_id; } if (settings.entry_id) { downloadUrl += '/entry_id/' + settings.entry_id; } var flashVarsString = this.flashVarsToString(settings.flashvars); var ks = settings.ks; if (ks) { downloadUrl += '/?ks=' + ks + flashVarsString; } else { downloadUrl += '/?' + flashVarsString.substr(1, flashVarsString.length); } return downloadUrl; }, /** * Get Kaltura thumb url from entry object * TODO We need to grab thumbnail path from api (baseEntry->thumbnailUrl) * or a specialized entry point for cases where we don't have the api is available * * @param {object} Entry settings used to generate the api url request */ getKalturaThumbUrl: function (settings) { //Check if external thumbnailUrl is defined if (settings.flashvars && settings.flashvars.thumbnailUrl !== undefined){ return settings.flashvars.thumbnailUrl; } var sizeParam = ''; if (settings.width != '100%' && settings.width) { sizeParam += '/width/' + parseInt(settings.width); } if (settings.height != '100%' && settings.height) { sizeParam += '/height/' + parseInt(settings.height); } // if no height or width is provided default to 480P if (!settings.height && !settings.width) { sizeParam += '/height/480'; } var vidParams = ''; if (settings.vid_sec) { vidParams += '/vid_sec/' + settings.vid_sec; } if (settings.vid_slices) { vidParams += '/vid_slices/' + settings.vid_slices; } // Add the ks if set ( flashvar overrides settings based ks ) if (settings.ks) { vidParams+= '/ks/' + settings.ks; } if (settings.flashvars && settings.flashvars.ks) { vidParams+= '/ks/' + settings.flashvars.ks; } var flashVars = {}; // Add referenceId if set if (settings.flashvars && settings.flashvars.referenceId) { flashVars[ 'referenceId' ] = settings.flashvars.referenceId; } if (settings.p && !settings.partner_id) { settings.partner_id = settings.p; } if (!settings.partner_id && settings.wid) { //this.log("Warning, please include partner_id in your embed settings"); settings.partner_id = settings.wid.replace('_', ''); } // Check for entryId var entryId = (settings.entry_id) ? '/entry_id/' + settings.entry_id : ''; // Return the thumbnail.php script which will redirect to the thumbnail location return this.getPath() + 'modules/KalturaSupport/thumbnail.php' + '/p/' + settings.partner_id + '/uiconf_id/' + settings.uiconf_id + entryId + sizeParam + vidParams + '?' + this.flashVarsToUrl(flashVars); }, /** * Get kaltura embed settings from a swf url and flashvars object * * @param {string} swfUrl * url to kaltura platform hosted swf * @param {object} flashvars * object mapping kaltura variables, ( overrides url based variables ) */ getEmbedSettings: function (swfUrl, flashvars) { var embedSettings = {}; // Convert flashvars if in string format: if (typeof flashvars == 'string') { flashvars = this.flashVars2Object(flashvars); } if (!flashvars) { flashvars = {}; } if (!swfUrl) { return {}; } var trim = function (str) { return str.replace(/^\s+|\s+$/g, ""); } // Include flashvars embedSettings.flashvars = flashvars; var dataUrlParts = swfUrl.split('/'); // Search backward for key value pairs var prevUrlPart = null; while (dataUrlParts.length) { var curUrlPart = dataUrlParts.pop(); switch (curUrlPart) { case 'p': embedSettings.wid = '_' + prevUrlPart; embedSettings.p = prevUrlPart; break; case 'wid': embedSettings.wid = prevUrlPart; embedSettings.p = prevUrlPart.replace(/_/, ''); break; case 'entry_id': embedSettings.entry_id = prevUrlPart; break; case 'uiconf_id': case 'ui_conf_id': embedSettings.uiconf_id = prevUrlPart; break; case 'cache_st': embedSettings.cache_st = prevUrlPart; break; } prevUrlPart = trim(curUrlPart); } // Add in Flash vars embedSettings ( they take precedence over embed url ) for (var key in flashvars) { var val = flashvars[key]; key = key.toLowerCase(); // Normalize to the url based settings: if (key == 'entryid') { embedSettings.entry_id = val; } if (key == 'uiconfid') { embedSettings.uiconf_id = val; } if (key == 'widgetid' || key == 'widget_id') { embedSettings.wid = val; } if (key == 'partnerid' || key == 'partner_id') { embedSettings.wid = '_' + val; embedSettings.p = val; } if (key == 'referenceid') { embedSettings.reference_id = val; } } // Always pass cache_st if (!embedSettings.cache_st) { embedSettings.cache_st = 1; } return embedSettings; }, /** * Converts a flashvar string to flashvars object * @param {String} flashvarsString * @return {Object} flashvars object */ flashVars2Object: function (flashvarsString) { var flashVarsSet = ( flashvarsString ) ? flashvarsString.split('&') : []; var flashvars = {}; for (var i = 0; i < flashVarsSet.length; i++) { var currentVar = flashVarsSet[i].split('='); if (currentVar[0] && currentVar[1]) { flashvars[ currentVar[0] ] = currentVar[1]; } } return flashvars; }, /** * Convert flashvars to a string * @param {object} flashVarsObject object to be string encoded */ flashVarsToString: function (flashVarsObject) { var params = ''; for (var i in flashVarsObject) { // check for object representation of plugin config: if (typeof flashVarsObject[i] == 'object') { for (var j in flashVarsObject[i]) { params += '&' + '' + encodeURIComponent(i) + '.' + encodeURIComponent(j) + '=' + encodeURIComponent(flashVarsObject[i][j]); } } else { params += '&' + '' + encodeURIComponent(i) + '=' + encodeURIComponent(flashVarsObject[i]); } } return params; }, /** * Converts a flashvar object into a url object string * @param {object} flashVarsObject object to be url encoded */ flashVarsToUrl: function (flashVarsObject) { var params = ''; for (var i in flashVarsObject) { var curVal = typeof flashVarsObject[i] == 'object'? JSON.stringify( flashVarsObject[i] ): flashVarsObject[i]; params += '&' + 'flashvars[' + encodeURIComponent(i) + ']=' + encodeURIComponent(curVal); } return params; }, /** * @return {boolean} true if page has audio video tags */ pageHasAudioOrVideoTags: function () { // if selector is set to false or is empty return false if (mw.getConfig('EmbedPlayer.RewriteSelector') === false || mw.getConfig('EmbedPlayer.RewriteSelector') == '') { return false; } // If document includes audio or video tags if (document.getElementsByTagName('video').length != 0 || document.getElementsByTagName('audio').length != 0) { return true; } return false; }, /** * Get the list of embed objects on the page that are 'kaltura players' */ getKalutaObjectList: function () { var _this = this; var kalturaPlayerList = []; // Check all objects for kaltura compatible urls var objectList = document.getElementsByTagName('object'); if (!objectList.length && document.getElementById('kaltura_player')) { objectList = [ document.getElementById('kaltura_player') ]; } // local function to attempt to add the kalturaEmbed var tryAddKalturaEmbed = function (url, flashvars) { //make sure we change only kdp objects if (!url.match(/(kwidget|kdp)/ig)) { return false; } var settings = _this.getEmbedSettings(url, flashvars); if (settings && settings.uiconf_id && settings.wid) { objectList[i].kEmbedSettings = settings; kalturaPlayerList.push(objectList[i]); return true; } return false; }; for (var i = 0; i < objectList.length; i++) { if (!objectList[i]) { continue; } var swfUrl = ''; var flashvars = {}; var paramTags = objectList[i].getElementsByTagName('param'); for (var j = 0; j < paramTags.length; j++) { var pName = paramTags[j].getAttribute('name').toLowerCase(); var pVal = paramTags[j].getAttribute('value'); if (pName == 'data' || pName == 'src' || pName == 'movie') { swfUrl = pVal; } if (pName == 'flashvars') { flashvars = this.flashVars2Object(pVal); } } if (tryAddKalturaEmbed(swfUrl, flashvars)) { continue; } // Check for object data style url: if (objectList[i].getAttribute('data')) { if (tryAddKalturaEmbed(objectList[i].getAttribute('data'), flashvars)) { continue; } } } return kalturaPlayerList; }, /** * Checks if the current page has jQuery defined, else include it and issue callback */ jQueryLoadCheck: function (callback) { if (!window.jQuery || !mw.versionIsAtLeast("1.7.2", window.jQuery.fn.jquery)) { // Set clientPagejQuery if already defined, if (window.jQuery) { window.clientPagejQuery = window.jQuery.noConflict(); // keep client page jQuery in $ window.$ = window.clientPagejQuery; } this.appendScriptUrl(this.getPath() + 'resources/jquery/jquery.min.js', function () { // remove jQuery from window scope if client has already included older jQuery window.kalturaJQuery = window.jQuery.noConflict(); // Restore client jquery to base target if (window.clientPagejQuery) { window.jQuery = window.$ = window.clientPagejQuery; } // Run all on-page code with kalturaJQuery scope // ( pass twice to poupluate $, and jQuery ) callback(window.kalturaJQuery, window.kalturaJQuery); }); } else { // update window.kalturaJQuery reference: window.kalturaJQuery = window.jQuery; callback(window.jQuery, window.jQuery); } }, // similar to jQuery.extend extend: function (obj) { var argSet = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < argSet.length; i++) { var source = argSet[i]; if (source) { for (var prop in source) { if (source[prop] && source[prop].constructor === Object) { if (!obj[prop] || obj[prop].constructor === Object) { obj[prop] = obj[prop] || {}; this.extend(obj[prop], source[prop]); } else { obj[prop] = source[prop]; } } else { obj[prop] = source[prop]; } } } } ; return obj; }, // similar to parm param: function (obj) { var o = ''; var and = ''; for (var i in obj) { o += and + i + '=' + encodeURIComponent(obj[i]); and = '&'; } return o; }, /** * Append a set of urls, and issue the callback once all have been loaded * @param {array} urls * @param {function} callback */ appendScriptUrls: function (urls, callback) { kWidget.log("appendScriptUrls"); var _this = this; var loadCount = 0; if (urls.length == 0) { if (callback) callback(); return; } for (var i = 0; i < urls.length; i++) { (function (inx) { _this.appendScriptUrl(urls[inx], function () { loadCount++; if (loadCount == urls.length) { if (callback) callback(); } }) })(i); } }, /** * Append a script to the dom: * @param {string} url * @param {function} done callback * @param {object} Document to append the script on * @param {function} error callback */ appendScriptUrl: function (url, callback, docContext, callbackError) { if (!docContext) { docContext = window.document; } var head = docContext.getElementsByTagName("head")[0] || docContext.documentElement; var script = docContext.createElement("script"); script.src = url; // Handle Script loading var done = false; // Attach handlers for all browsers script.onload = script.onerror = script.onreadystatechange = function () { if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) { done = true; if (arguments && arguments[0] && arguments[0].type) { if (arguments[0].type == "error") { if (typeof callbackError == "function") { callbackError(); } } else { if (typeof callback == "function") { callback(); } } } else { if (typeof callback == "function") { callback(); } } // Handle memory leak in IE script.onload = script.onerror = script.onreadystatechange = null; if (head && script.parentNode) { head.removeChild(script); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore(script, head.firstChild); }, /** * Add css to the dom * @param {string} url to append to the dom */ appendCssUrl: function (url, context) { context = context || document; var head = context.getElementsByTagName("head")[0]; var cssNode = context.createElement('link'); cssNode.setAttribute("rel", "stylesheet"); cssNode.setAttribute("type", "text/css"); cssNode.setAttribute("href", url); // cssNode.setAttribute("media","screen"); head.appendChild(cssNode); }, /** * Converts service configuration to url params */ serviceConfigToUrl: function () { var serviceVars = ['ServiceUrl', 'CdnUrl', 'ServiceBase', 'UseManifestUrls']; var urlParam = ''; for (var i = 0; i < serviceVars.length; i++) { if (mw.getConfig('Kaltura.' + serviceVars[i]) !== null) { urlParam += '&' + serviceVars[i] + '=' + encodeURIComponent(mw.getConfig('Kaltura.' + serviceVars[i])); } } return urlParam; }, /** * Abstract support for adding events uses: * http://ejohn.org/projects/flexible-javascript-events/ */ addEvent: function (obj, type, fn, useCapture) { if (obj.attachEvent) { obj['e' + type + fn] = fn; obj[type + fn] = function () { obj['e' + type + fn](window.event); } obj.attachEvent('on' + type, obj[type + fn]); } else { obj.addEventListener(type, fn, !!useCapture); } }, /** * Abstract support for removing events uses */ removeEvent: function (obj, type, fn) { if (obj.detachEvent) { obj.detachEvent('on' + type, obj[type + fn]); obj[type + fn] = null; } else { obj.removeEventListener(type, fn, false); } }, /** * Check if object is empty */ isEmptyObject: function (obj) { var name; for (name in obj) { return false; } return true; }, /** * Converts settings to url params * @param {object} settings Settings to be convert into url params */ embedSettingsToUrl: function (settings) { var url = ''; var kalturaAttributeList = ['uiconf_id', 'entry_id', 'wid', 'p', 'cache_st']; for (var attrKey in settings) { // Check if the attrKey is in the kalturaAttributeList: for (var i = 0; i < kalturaAttributeList.length; i++) { if (kalturaAttributeList[i] == attrKey) { url += '&' + attrKey + '=' + encodeURIComponent(settings[attrKey]); } } } // Add the flashvars: url += this.flashVarsToUrl(settings.flashvars); return url; }, /** * Overrides flash embed methods, as to optionally support HTML5 injection */ overrideFlashEmbedMethods: function () { var _this = this; var doEmbedSettingsWrite = function (settings, replaceTargetId, widthStr, heightStr) { if (widthStr) { settings.width = widthStr; } if (heightStr) { settings.height = heightStr; } kWidget.embed(replaceTargetId, settings); }; // flashobject if (window['flashembed'] && !window['originalFlashembed']) { window['originalFlashembed'] = window['flashembed']; window['flashembed'] = function (targetId, attributes, flashvars) { // TODO test with kWidget.embed replacement. _this.domReady(function () { var kEmbedSettings = kWidget.getEmbedSettings(attributes.src, flashvars); if (kEmbedSettings.uiconf_id && ( kWidget.isHTML5FallForward() || !kWidget.supportsFlash() )) { document.getElementById(targetId).innerHTML = '<div style="width:100%;height:100%" id="' + attributes.id + '"></div>'; doEmbedSettingsWrite(kEmbedSettings, attributes.id, attributes.width, attributes.height); } else { // Use the original flash player embed: return originalFlashembed(targetId, attributes, flashvars); } }); }; // add static methods var flashembedStaticMethods = ['asString', 'getHTML', 'getVersion', 'isSupported']; for (var i = 0; i < flashembedStaticMethods.length; i++) { window['flashembed'][ flashembedStaticMethods[i] ] = originalFlashembed } } // SWFObject v 1.5 if (window['SWFObject'] && !window['SWFObject'].prototype['originalWrite']) { window['SWFObject'].prototype['originalWrite'] = window['SWFObject'].prototype.write; window['SWFObject'].prototype['write'] = function (targetId) { var swfObj = this; // TODO test with kWidget.embed replacement. _this.domReady(function () { var kEmbedSettings = kWidget.getEmbedSettings(swfObj.attributes.swf, swfObj.params.flashVars); if (kEmbedSettings.uiconf_id && ( kWidget.isHTML5FallForward() || !kWidget.supportsFlash() )) { doEmbedSettingsWrite(kEmbedSettings, targetId, swfObj.attributes.width, swfObj.attributes.height); } else { // use the original flash player embed: swfObj.originalWrite(targetId); } }); }; } // SWFObject v 2.x if (window['swfobject'] && !window['swfobject']['originalEmbedSWF']) { window['swfobject']['originalEmbedSWF'] = window['swfobject']['embedSWF']; // Override embedObject for our own ends window['swfobject']['embedSWF'] = function (swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { // TODO test with kWidget.embed replacement. _this.domReady(function () { var kEmbedSettings = kWidget.getEmbedSettings(swfUrlStr, flashvarsObj); // Check if IsHTML5FallForward if (kEmbedSettings.uiconf_id && ( kWidget.isHTML5FallForward() || !kWidget.supportsFlash() )) { doEmbedSettingsWrite(kEmbedSettings, replaceElemIdStr, widthStr, heightStr); } else { // Else call the original EmbedSWF with all its arguments window['swfobject']['originalEmbedSWF'](swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn); } }); }; } } }; // Export to kWidget and KWidget ( official name is camel case kWidget ) window.KWidget = kWidget; window.kWidget = kWidget; })(window.jQuery);
fix: fix thumb embed due to Safari user gesture restriction
kWidget/kWidget.js
fix: fix thumb embed due to Safari user gesture restriction
<ide><path>Widget/kWidget.js <ide> } <ide> <ide> // Check if we need to capture a play event ( iOS sync embed call ) <del> if (settings.captureClickEventForiOS && (this.isIOS() || this.isAndroid())) { <add> if (settings.captureClickEventForiOS && (this.isSafari() || this.isAndroid())) { <ide> this.captureClickWrapedIframeUpdate(targetId, requestSettings, iframe); <ide> } else { <ide> // get the callback name:
Java
agpl-3.0
error: pathspec 'core/src/main/java/bisq/core/api/model/PaymentAccountTypeAdapter.java' did not match any file(s) known to git
c25debaf99f11d6037c075b48d39efb43f4e8843
1
bitsquare/bitsquare,bitsquare/bitsquare,bisq-network/exchange,bisq-network/exchange
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.api.model; import bisq.core.locale.Country; import bisq.core.locale.FiatCurrency; import bisq.core.payment.CountryBasedPaymentAccount; import bisq.core.payment.PaymentAccount; import bisq.core.payment.payload.PaymentAccountPayload; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import lombok.extern.slf4j.Slf4j; import static bisq.common.util.ReflectionUtils.getSetterMethodForFieldInClassHierarchy; import static bisq.common.util.ReflectionUtils.getVisibilityModifierAsString; import static bisq.common.util.ReflectionUtils.isSetterOnClass; import static bisq.common.util.ReflectionUtils.loadFieldListForClassHierarchy; import static bisq.core.locale.CountryUtil.findCountryByCode; import static bisq.core.locale.CurrencyUtil.getCurrencyByCountryCode; import static com.google.common.base.Preconditions.checkNotNull; import static java.lang.String.format; import static java.util.Comparator.comparing; @Slf4j class PaymentAccountTypeAdapter extends TypeAdapter<PaymentAccount> { private final Class<? extends PaymentAccount> paymentAccountType; private final Class<? extends PaymentAccountPayload> paymentAccountPayloadType; private final Map<Field, Optional<Method>> fieldSettersMap; private final Predicate<Field> isExcludedField; /** * Constructor used when de-serializing a json payment account form into a * PaymentAccount instance. * * @param paymentAccountType the PaymentAccount subclass being instantiated */ public PaymentAccountTypeAdapter(Class<? extends PaymentAccount> paymentAccountType) { this(paymentAccountType, new String[]{}); } /** * Constructor used when serializing a PaymentAccount subclass instance into a json * payment account json form. * * @param paymentAccountType the PaymentAccount subclass being serialized * @param excludedFields a string array of field names to exclude from the serialized * payment account json form. */ public PaymentAccountTypeAdapter(Class<? extends PaymentAccount> paymentAccountType, String[] excludedFields) { this.paymentAccountType = paymentAccountType; this.paymentAccountPayloadType = getPaymentAccountPayloadType(); this.isExcludedField = (f) -> Arrays.stream(excludedFields).anyMatch(e -> e.equals(f.getName())); this.fieldSettersMap = getFieldSetterMap(); } @Override public void write(JsonWriter out, PaymentAccount account) throws IOException { // We write a blank payment acct form for a payment method id. // We're not serializing a real payment account instance here. if (log.isDebugEnabled()) log.debug("Writing PaymentAccount json form for fields with accessors..."); out.beginObject(); writeCommonFields(out, account); fieldSettersMap.forEach((field, value) -> { try { // Write out a json element if there is a @Setter for this field. if (value.isPresent()) { if (log.isDebugEnabled()) log.debug("Append form with settable field: {} {} {} setter: {}", getVisibilityModifierAsString(field), field.getType().getSimpleName(), field.getName(), value); String fieldName = field.getName(); out.name(fieldName); out.value("Your " + fieldName.toLowerCase()); } } catch (Exception ex) { throw new IllegalStateException( format("Could not serialize a %s to json", account.getClass().getSimpleName()), ex); } }); out.endObject(); if (log.isDebugEnabled()) log.debug("Done writing PaymentAccount json form."); } @Override public PaymentAccount read(JsonReader in) throws IOException { if (log.isDebugEnabled()) log.debug("De-serializing json to new {} ...", paymentAccountType.getSimpleName()); PaymentAccount account = initNewPaymentAccount(); in.beginObject(); while (in.hasNext()) { String currentFieldName = in.nextName(); // Some of the fields are common to all payment account types. if (didReadCommonField(in, account, currentFieldName)) continue; // If the account is a subclass of CountryBasedPaymentAccount, set the // account's Country, and use the Country to derive and set the account's // FiatCurrency. if (didReadCountryField(in, account, currentFieldName)) continue; try { Optional<Field> field = fieldSettersMap.keySet().stream() .filter(k -> k.getName().equals(currentFieldName)).findFirst(); field.ifPresentOrElse((f) -> invokeSetterMethod(account, f, in), () -> { throw new IllegalStateException( format("Could not de-serialize json to a '%s' because there is no %s field.", account.getClass().getSimpleName(), currentFieldName)); }); } catch (Exception ex) { throw new IllegalStateException( format("Could not de-serialize json to a '%s'.", account.getClass().getSimpleName()), ex); } } in.endObject(); if (log.isDebugEnabled()) log.debug("Done de-serializing json."); return account; } private void invokeSetterMethod(PaymentAccount account, Field field, JsonReader jsonReader) { Optional<Method> setter = fieldSettersMap.get(field); if (setter.isPresent()) { try { // The setter might be on the PaymentAccount instance, or its // PaymentAccountPayload instance. if (isSetterOnPaymentAccountClass(setter.get(), account)) { setter.get().invoke(account, nextStringOrNull(jsonReader)); } else if (isSetterOnPaymentAccountPayloadClass(setter.get(), account)) { setter.get().invoke(account.getPaymentAccountPayload(), nextStringOrNull(jsonReader)); } else { String exMsg = format("Could not de-serialize json to a '%s' using reflection" + " because the setter's declaring class was not found.", account.getClass().getSimpleName()); throw new IllegalStateException(exMsg); } } catch (IllegalAccessException | InvocationTargetException ex) { throw new IllegalStateException( format("Could not de-serialize json to a '%s' due to reflection error.", account.getClass().getSimpleName()), ex); } } else { throw new IllegalStateException( format("Could not de-serialize json to a '%s' because there is no setter for field %s.", account.getClass().getSimpleName(), field.getName())); } } private boolean isSetterOnPaymentAccountClass(Method setter, PaymentAccount account) { return isSetterOnClass(setter, account.getClass()); } private boolean isSetterOnPaymentAccountPayloadClass(Method setter, PaymentAccount account) { return isSetterOnClass(setter, account.getPaymentAccountPayload().getClass()) || isSetterOnClass(setter, account.getPaymentAccountPayload().getClass().getSuperclass()); } private Map<Field, Optional<Method>> getFieldSetterMap() { List<Field> orderedFields = getOrderedFields(); Map<Field, Optional<Method>> map = new LinkedHashMap<>(); for (Field field : orderedFields) { Optional<Method> setter = getSetterMethodForFieldInClassHierarchy(field, paymentAccountType) .or(() -> getSetterMethodForFieldInClassHierarchy(field, paymentAccountPayloadType)); map.put(field, setter); } return Collections.unmodifiableMap(map); } private List<Field> getOrderedFields() { List<Field> fields = new ArrayList<>(); loadFieldListForClassHierarchy(fields, paymentAccountType, isExcludedField); loadFieldListForClassHierarchy(fields, paymentAccountPayloadType, isExcludedField); fields.sort(comparing(Field::getName)); return fields; } private String nextStringOrNull(JsonReader in) { try { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } else { return in.nextString(); } } catch (IOException ex) { throw new IllegalStateException("Could not peek at next String value in JsonReader.", ex); } } @SuppressWarnings("unused") private Long nextLongOrNull(JsonReader in) { try { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } else { return in.nextLong(); } } catch (IOException ex) { throw new IllegalStateException("Could not peek at next Long value in JsonReader.", ex); } } private void writeCommonFields(JsonWriter out, PaymentAccount account) throws IOException { if (log.isDebugEnabled()) log.debug("writeCommonFields(out, {}) -> paymentMethodId = {}", account, account.getPaymentMethod().getId()); out.name("_COMMENT_"); out.value("Please do not edit the paymentMethodId field."); out.name("paymentMethodId"); out.value(account.getPaymentMethod().getId()); } private boolean didReadCommonField(JsonReader in, PaymentAccount account, String fieldName) { switch (fieldName) { case "_COMMENT_": case "paymentMethodId": // skip nextStringOrNull(in); return true; case "accountName": account.setAccountName(nextStringOrNull(in)); return true; default: return false; } } private boolean didReadCountryField(JsonReader in, PaymentAccount account, String fieldName) { if (account.isCountryBasedPaymentAccount() && fieldName.equals("country")) { // Read the country code, and use it to set the account's country and single // trade currency fields. String countryCode = nextStringOrNull(in); Optional<Country> country = findCountryByCode(countryCode); if (country.isPresent()) { ((CountryBasedPaymentAccount) account).setCountry(country.get()); FiatCurrency fiatCurrency = getCurrencyByCountryCode(checkNotNull(countryCode)); account.setSingleTradeCurrency(fiatCurrency); return true; } else { throw new IllegalStateException( format("Could not de-serialize json to a '%s' because %s is an invalid country code.", account.getClass().getSimpleName(), countryCode)); } } else { return false; } } private Class<? extends PaymentAccountPayload> getPaymentAccountPayloadType() { try { Package pkg = PaymentAccountPayload.class.getPackage(); //noinspection unchecked return (Class<? extends PaymentAccountPayload>) Class.forName(pkg.getName() + "." + paymentAccountType.getSimpleName() + "Payload"); } catch (Exception ex) { throw new IllegalStateException( format("Could not get payload class for %s", paymentAccountType.getSimpleName()), ex); } } private PaymentAccount initNewPaymentAccount() { try { Constructor<?> constructor = paymentAccountType.getDeclaredConstructor(); PaymentAccount paymentAccount = (PaymentAccount) constructor.newInstance(); paymentAccount.init(); return paymentAccount; } catch (NoSuchMethodException ex) { throw new IllegalStateException(format("No default declared constructor found for class %s", paymentAccountType.getSimpleName()), ex); } catch (IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw new IllegalStateException(format("Could not instantiate class %s", paymentAccountType.getSimpleName()), ex); } } }
core/src/main/java/bisq/core/api/model/PaymentAccountTypeAdapter.java
Add new (gson) PaymentAccountTypeAdapter to core.api.model This class does most of the work of the api's (create) PaymentAccount json form serialization/de-serialization.
core/src/main/java/bisq/core/api/model/PaymentAccountTypeAdapter.java
Add new (gson) PaymentAccountTypeAdapter to core.api.model
<ide><path>ore/src/main/java/bisq/core/api/model/PaymentAccountTypeAdapter.java <add>/* <add> * This file is part of Bisq. <add> * <add> * Bisq is free software: you can redistribute it and/or modify it <add> * under the terms of the GNU Affero General Public License as published by <add> * the Free Software Foundation, either version 3 of the License, or (at <add> * your option) any later version. <add> * <add> * Bisq is distributed in the hope that it will be useful, but WITHOUT <add> * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or <add> * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public <add> * License for more details. <add> * <add> * You should have received a copy of the GNU Affero General Public License <add> * along with Bisq. If not, see <http://www.gnu.org/licenses/>. <add> */ <add> <add>package bisq.core.api.model; <add> <add> <add>import bisq.core.locale.Country; <add>import bisq.core.locale.FiatCurrency; <add>import bisq.core.payment.CountryBasedPaymentAccount; <add>import bisq.core.payment.PaymentAccount; <add>import bisq.core.payment.payload.PaymentAccountPayload; <add> <add>import com.google.gson.TypeAdapter; <add>import com.google.gson.stream.JsonReader; <add>import com.google.gson.stream.JsonToken; <add>import com.google.gson.stream.JsonWriter; <add> <add>import java.io.IOException; <add> <add>import java.util.ArrayList; <add>import java.util.Arrays; <add>import java.util.Collections; <add>import java.util.LinkedHashMap; <add>import java.util.List; <add>import java.util.Map; <add>import java.util.Optional; <add>import java.util.function.Predicate; <add> <add>import java.lang.reflect.Constructor; <add>import java.lang.reflect.Field; <add>import java.lang.reflect.InvocationTargetException; <add>import java.lang.reflect.Method; <add> <add>import lombok.extern.slf4j.Slf4j; <add> <add>import static bisq.common.util.ReflectionUtils.getSetterMethodForFieldInClassHierarchy; <add>import static bisq.common.util.ReflectionUtils.getVisibilityModifierAsString; <add>import static bisq.common.util.ReflectionUtils.isSetterOnClass; <add>import static bisq.common.util.ReflectionUtils.loadFieldListForClassHierarchy; <add>import static bisq.core.locale.CountryUtil.findCountryByCode; <add>import static bisq.core.locale.CurrencyUtil.getCurrencyByCountryCode; <add>import static com.google.common.base.Preconditions.checkNotNull; <add>import static java.lang.String.format; <add>import static java.util.Comparator.comparing; <add> <add>@Slf4j <add>class PaymentAccountTypeAdapter extends TypeAdapter<PaymentAccount> { <add> <add> private final Class<? extends PaymentAccount> paymentAccountType; <add> private final Class<? extends PaymentAccountPayload> paymentAccountPayloadType; <add> private final Map<Field, Optional<Method>> fieldSettersMap; <add> private final Predicate<Field> isExcludedField; <add> <add> /** <add> * Constructor used when de-serializing a json payment account form into a <add> * PaymentAccount instance. <add> * <add> * @param paymentAccountType the PaymentAccount subclass being instantiated <add> */ <add> public PaymentAccountTypeAdapter(Class<? extends PaymentAccount> paymentAccountType) { <add> this(paymentAccountType, new String[]{}); <add> } <add> <add> /** <add> * Constructor used when serializing a PaymentAccount subclass instance into a json <add> * payment account json form. <add> * <add> * @param paymentAccountType the PaymentAccount subclass being serialized <add> * @param excludedFields a string array of field names to exclude from the serialized <add> * payment account json form. <add> */ <add> public PaymentAccountTypeAdapter(Class<? extends PaymentAccount> paymentAccountType, String[] excludedFields) { <add> this.paymentAccountType = paymentAccountType; <add> this.paymentAccountPayloadType = getPaymentAccountPayloadType(); <add> this.isExcludedField = (f) -> Arrays.stream(excludedFields).anyMatch(e -> e.equals(f.getName())); <add> this.fieldSettersMap = getFieldSetterMap(); <add> } <add> <add> @Override <add> public void write(JsonWriter out, PaymentAccount account) throws IOException { <add> // We write a blank payment acct form for a payment method id. <add> // We're not serializing a real payment account instance here. <add> if (log.isDebugEnabled()) <add> log.debug("Writing PaymentAccount json form for fields with accessors..."); <add> <add> out.beginObject(); <add> writeCommonFields(out, account); <add> fieldSettersMap.forEach((field, value) -> { <add> try { <add> // Write out a json element if there is a @Setter for this field. <add> if (value.isPresent()) { <add> if (log.isDebugEnabled()) <add> log.debug("Append form with settable field: {} {} {} setter: {}", <add> getVisibilityModifierAsString(field), <add> field.getType().getSimpleName(), <add> field.getName(), <add> value); <add> <add> String fieldName = field.getName(); <add> out.name(fieldName); <add> out.value("Your " + fieldName.toLowerCase()); <add> } <add> } catch (Exception ex) { <add> throw new IllegalStateException( <add> format("Could not serialize a %s to json", account.getClass().getSimpleName()), ex); <add> } <add> }); <add> out.endObject(); <add> if (log.isDebugEnabled()) <add> log.debug("Done writing PaymentAccount json form."); <add> } <add> <add> @Override <add> public PaymentAccount read(JsonReader in) throws IOException { <add> if (log.isDebugEnabled()) <add> log.debug("De-serializing json to new {} ...", paymentAccountType.getSimpleName()); <add> <add> PaymentAccount account = initNewPaymentAccount(); <add> in.beginObject(); <add> while (in.hasNext()) { <add> String currentFieldName = in.nextName(); <add> <add> // Some of the fields are common to all payment account types. <add> if (didReadCommonField(in, account, currentFieldName)) <add> continue; <add> <add> // If the account is a subclass of CountryBasedPaymentAccount, set the <add> // account's Country, and use the Country to derive and set the account's <add> // FiatCurrency. <add> if (didReadCountryField(in, account, currentFieldName)) <add> continue; <add> <add> try { <add> Optional<Field> field = fieldSettersMap.keySet().stream() <add> .filter(k -> k.getName().equals(currentFieldName)).findFirst(); <add> <add> field.ifPresentOrElse((f) -> invokeSetterMethod(account, f, in), () -> { <add> throw new IllegalStateException( <add> format("Could not de-serialize json to a '%s' because there is no %s field.", <add> account.getClass().getSimpleName(), <add> currentFieldName)); <add> }); <add> } catch (Exception ex) { <add> throw new IllegalStateException( <add> format("Could not de-serialize json to a '%s'.", <add> account.getClass().getSimpleName()), ex); <add> } <add> } <add> in.endObject(); <add> if (log.isDebugEnabled()) <add> log.debug("Done de-serializing json."); <add> <add> return account; <add> } <add> <add> private void invokeSetterMethod(PaymentAccount account, Field field, JsonReader jsonReader) { <add> Optional<Method> setter = fieldSettersMap.get(field); <add> if (setter.isPresent()) { <add> try { <add> // The setter might be on the PaymentAccount instance, or its <add> // PaymentAccountPayload instance. <add> if (isSetterOnPaymentAccountClass(setter.get(), account)) { <add> setter.get().invoke(account, nextStringOrNull(jsonReader)); <add> } else if (isSetterOnPaymentAccountPayloadClass(setter.get(), account)) { <add> setter.get().invoke(account.getPaymentAccountPayload(), nextStringOrNull(jsonReader)); <add> } else { <add> String exMsg = format("Could not de-serialize json to a '%s' using reflection" <add> + " because the setter's declaring class was not found.", <add> account.getClass().getSimpleName()); <add> throw new IllegalStateException(exMsg); <add> } <add> } catch (IllegalAccessException | InvocationTargetException ex) { <add> throw new IllegalStateException( <add> format("Could not de-serialize json to a '%s' due to reflection error.", <add> account.getClass().getSimpleName()), ex); <add> } <add> } else { <add> throw new IllegalStateException( <add> format("Could not de-serialize json to a '%s' because there is no setter for field %s.", <add> account.getClass().getSimpleName(), <add> field.getName())); <add> } <add> } <add> <add> private boolean isSetterOnPaymentAccountClass(Method setter, PaymentAccount account) { <add> return isSetterOnClass(setter, account.getClass()); <add> } <add> <add> private boolean isSetterOnPaymentAccountPayloadClass(Method setter, PaymentAccount account) { <add> return isSetterOnClass(setter, account.getPaymentAccountPayload().getClass()) <add> || isSetterOnClass(setter, account.getPaymentAccountPayload().getClass().getSuperclass()); <add> } <add> <add> private Map<Field, Optional<Method>> getFieldSetterMap() { <add> List<Field> orderedFields = getOrderedFields(); <add> Map<Field, Optional<Method>> map = new LinkedHashMap<>(); <add> for (Field field : orderedFields) { <add> Optional<Method> setter = getSetterMethodForFieldInClassHierarchy(field, paymentAccountType) <add> .or(() -> getSetterMethodForFieldInClassHierarchy(field, paymentAccountPayloadType)); <add> map.put(field, setter); <add> } <add> return Collections.unmodifiableMap(map); <add> } <add> <add> private List<Field> getOrderedFields() { <add> List<Field> fields = new ArrayList<>(); <add> loadFieldListForClassHierarchy(fields, paymentAccountType, isExcludedField); <add> loadFieldListForClassHierarchy(fields, paymentAccountPayloadType, isExcludedField); <add> fields.sort(comparing(Field::getName)); <add> return fields; <add> } <add> <add> private String nextStringOrNull(JsonReader in) { <add> try { <add> if (in.peek() == JsonToken.NULL) { <add> in.nextNull(); <add> return null; <add> } else { <add> return in.nextString(); <add> } <add> } catch (IOException ex) { <add> throw new IllegalStateException("Could not peek at next String value in JsonReader.", ex); <add> } <add> } <add> <add> @SuppressWarnings("unused") <add> private Long nextLongOrNull(JsonReader in) { <add> try { <add> if (in.peek() == JsonToken.NULL) { <add> in.nextNull(); <add> return null; <add> } else { <add> return in.nextLong(); <add> } <add> } catch (IOException ex) { <add> throw new IllegalStateException("Could not peek at next Long value in JsonReader.", ex); <add> } <add> } <add> <add> private void writeCommonFields(JsonWriter out, PaymentAccount account) throws IOException { <add> if (log.isDebugEnabled()) <add> log.debug("writeCommonFields(out, {}) -> paymentMethodId = {}", <add> account, account.getPaymentMethod().getId()); <add> <add> out.name("_COMMENT_"); <add> out.value("Please do not edit the paymentMethodId field."); <add> <add> out.name("paymentMethodId"); <add> out.value(account.getPaymentMethod().getId()); <add> } <add> <add> private boolean didReadCommonField(JsonReader in, PaymentAccount account, String fieldName) { <add> switch (fieldName) { <add> case "_COMMENT_": <add> case "paymentMethodId": <add> // skip <add> nextStringOrNull(in); <add> return true; <add> case "accountName": <add> account.setAccountName(nextStringOrNull(in)); <add> return true; <add> default: <add> return false; <add> } <add> } <add> <add> private boolean didReadCountryField(JsonReader in, PaymentAccount account, String fieldName) { <add> if (account.isCountryBasedPaymentAccount() && fieldName.equals("country")) { <add> // Read the country code, and use it to set the account's country and single <add> // trade currency fields. <add> String countryCode = nextStringOrNull(in); <add> Optional<Country> country = findCountryByCode(countryCode); <add> if (country.isPresent()) { <add> ((CountryBasedPaymentAccount) account).setCountry(country.get()); <add> FiatCurrency fiatCurrency = getCurrencyByCountryCode(checkNotNull(countryCode)); <add> account.setSingleTradeCurrency(fiatCurrency); <add> return true; <add> } else { <add> throw new IllegalStateException( <add> format("Could not de-serialize json to a '%s' because %s is an invalid country code.", <add> account.getClass().getSimpleName(), countryCode)); <add> } <add> } else { <add> return false; <add> } <add> } <add> <add> private Class<? extends PaymentAccountPayload> getPaymentAccountPayloadType() { <add> try { <add> Package pkg = PaymentAccountPayload.class.getPackage(); <add> //noinspection unchecked <add> return (Class<? extends PaymentAccountPayload>) Class.forName(pkg.getName() <add> + "." + paymentAccountType.getSimpleName() + "Payload"); <add> } catch (Exception ex) { <add> throw new IllegalStateException( <add> format("Could not get payload class for %s", <add> paymentAccountType.getSimpleName()), ex); <add> } <add> } <add> <add> private PaymentAccount initNewPaymentAccount() { <add> try { <add> Constructor<?> constructor = paymentAccountType.getDeclaredConstructor(); <add> PaymentAccount paymentAccount = (PaymentAccount) constructor.newInstance(); <add> paymentAccount.init(); <add> return paymentAccount; <add> } catch (NoSuchMethodException ex) { <add> throw new IllegalStateException(format("No default declared constructor found for class %s", <add> paymentAccountType.getSimpleName()), ex); <add> } catch (IllegalAccessException | InstantiationException | InvocationTargetException ex) { <add> throw new IllegalStateException(format("Could not instantiate class %s", <add> paymentAccountType.getSimpleName()), ex); <add> } <add> } <add>}
JavaScript
mit
5da11203e674da652f74cecd0def2a021e9e0991
0
phetsims/scenery,phetsims/scenery,phetsims/scenery
// Copyright 2021, University of Colorado Boulder /** * A trait for Node that supports the Voicing feature, under accessibility. Allows you to define responses for the Node * and make requests to speak that content using HTML5 SpeechSynthesis and the UtteranceQueue. Voicing content is * organized into four categories which are responsible for describing different things. Output of this content * can be controlled by the voicingManager. These include the * * - "Name" response: The name of the object that uses Voicing. Similar to the "Accessible Name" in web accessibility. * - "Object" response: The state information about the object that uses Voicing. * - "Context" response: The contextual changes that result from interaction with the Node that uses Voicing. * - "Hint" response: A supporting hint that guides the user toward a desired interaction with this Node. * * See the property and setter documentation for each of these responses for more information. * * Once this content is set, you can make a request to speak it using an UtteranceQueue with one of the provided * functions in this Trait. It is up to you to call one of these functions when you wish for speech to be made. The only * exception is on the 'focus' event. Every Node that composes Voicing will speak its responses by when it * receives focus. * * @author Jesse Greenberg (PhET Interactive Simulations) */ import extend from '../../../../phet-core/js/extend.js'; import inheritance from '../../../../phet-core/js/inheritance.js'; import merge from '../../../../phet-core/js/merge.js'; import Node from '../../nodes/Node.js'; import scenery from '../../scenery.js'; import MouseHighlighting from './MouseHighlighting.js'; import voicingManager from './voicingManager.js'; import VoicingResponsePatterns from './VoicingResponsePatterns.js'; import voicingUtteranceQueue from './voicingUtteranceQueue.js'; // options that are supported by Voicing.js. Added to mutator keys so that Voicing properties can be set with mutate. const VOICING_OPTION_KEYS = [ 'voicingNameResponse', 'voicingObjectResponse', 'voicingContextResponse', 'voicingHintResponse', 'voicingUtteranceQueue' ]; const Voicing = { compose( type ) { assert && assert( _.includes( inheritance( type ), Node ), 'Only Node subtypes should compose Voicing' ); const proto = type.prototype; // compose with mouse highlighting MouseHighlighting.compose( type ); extend( proto, { /** * {Array.<string>} - String keys for all of the allowed options that will be set by node.mutate( options ), in * the order they will be evaluated. * @protected * * NOTE: See Node's _mutatorKeys documentation for more information on how this operates, and potential special * cases that may apply. */ _mutatorKeys: VOICING_OPTION_KEYS.concat( proto._mutatorKeys ), /** * Initialize in the type being composed with Voicing. Call this in the constructor. * @param {Object} [options] - NOTE: much of the time, the Node this composes into will call mutate for you, be careful not to double call. * @public */ initializeVoicing( options ) { assert && assert( this.voicing === undefined, 'Voicing has already been initialized for this Node' ); // initialize "super" Trait to support highlights on mouse input this.initializeMouseHighlighting(); // @public (read-only, scenery-internal) - flag indicating that this Node is composed with Voicing functionality this.voicing = true; // @private {string|null} - The response to be spoken for this Node when speaking names. This is usually // the accessible name for the Node, typically spoken on focus and on interaction, labelling what the object is. this._voicingNameResponse = null; // @private {string|null} - The response to be spoken for this node when speaking about object changes. This // is usually the state information directly associated with this Node, such as its current input value. this._voicingObjectResponse = null; // @private {string|null} - The response to be spoken for this node when speaking about context changes. // This is usually a response that describes the surrounding changes that have occurred after interacting // with the object. this._voicingContextResponse = null; // @private {string|null} - The response to be spoken when speaking hints. This is usually the response // that guides the user toward further interaction with this object if it is important to do so to use // the application. this._voicingHintResponse = null; // @private {boolean} - Controls whether or not object, context, and hint responses are controlled // by voicingManager Properties. If true, all responses will be spoken when requested, regardless // of these Properties. This is often useful for surrounding UI components where it is important // that information be heard even when certain responses have been disabled. this._voicingIgnoreVoicingManagerProperties = false; // @private {UtteranceQueue} - The utteranceQueue that responses for this Node will be spoken through. // By default, it will go through the singleton voicingUtteranceQueue, but you may need separate // UtteranceQueues for different areas of content in your application. For example, Voicing and // the default voicingUtteranceQueue may be disabled, but you could still want some speech to come through // while user is changing preferences or other settings. this._voicingUtteranceQueue = null; // {Object} - A collection of response patterns that are used to collect the responses of this Voicing Node // with voicingManager. Controls the order of the Voicing responses and even punctuation used when responses // are assembled into final content for the UtteranceQueue. See VoicingResponsePatterns for more details. this._voicingResponsePatterns = VoicingResponsePatterns.DEFAULT_RESPONSE_PATTERNS; // @private {Object} - Input listener that speaks content on focus. This is the only input listener added // by Voicing, but it is the one that is consistent for all Voicing nodes. On focus, speak the name, object // response, and interaction hint. this.speakContentOnFocusListener = { focus: event => { this.voicingSpeakFullResponse( { contextResponse: null } ); } }; this.addInputListener( this.speakContentOnFocusListener ); // support passing options through directly on initialize if ( options ) { this.mutate( _.pick( options, VOICING_OPTION_KEYS ) ); } }, /** * Speak all responses assigned to this Node. Options allow you to override a responses for this particular * speech request. Each response is only spoken if the associated Property of voicingManager is true. If * all are Properties are false, nothing will be spoken. * @public * * @param {Object} [options] */ voicingSpeakFullResponse( options ) { // options are passed along to collectAndSpeakResponse, see that function for additional options options = merge( { nameResponse: this._voicingNameResponse, objectResponse: this._voicingObjectResponse, contextResponse: this._voicingContextResponse, hintResponse: this._voicingHintResponse }, options ); this.collectAndSpeakResponse( options ); }, /** * Speak ONLY the provided responses that you pass in with options. This will NOT speak the name, object, * context, or hint responses assigned to this node by default. But it allows for clarity at usages so it is * clear that you are only requesting certain responses. If you want to speak all of the responses assigned * to this Node, use voicingSpeakFullResponse(). * * Each response will only be spoken if the Properties of voicingManager are true. If all of those are false, * nothing will be spoken. * @public * * @param {Object} [options] */ voicingSpeakResponse( options ) { // options are passed along to collectAndSpeakResponse, see that function for additional options options = merge( { nameResponse: null, objectResponse: null, contextResponse: null, hintResponse: null }, options ); this.collectAndSpeakResponse( options ); }, /** * Speak only the name response assigned to this Node. * @param options */ voicingSpeakNameResponse( options ) { // options are passed along to collectAndSpeakResponse, see that function for additional options options = merge( { nameResponse: this._voicingNameResponse }, options ); this.collectAndSpeakResponse( options ); }, /** * Speak only the object response assigned to this Node. * @public * * @param {Object} [options] */ voicingSpeakObjectResponse( options ) { // options are passed along to collectAndSpeakResponse, see that function for additional options options = merge( { objectResponse: this._voicingObjectResponse }, options ); this.collectAndSpeakResponse( options ); }, /** * Speak only the context response assigned to this Node. * @public * * @param {Object} [options] */ voicingSpeakContextResponse( options ) { // options are passed along to collectAndSpeakResponse, see that function for additional options options = merge( { contextResponse: this._voicingContextResponse }, options ); this.collectAndSpeakResponse( options ); }, /** * Speak only the hint response assigned to this Node. * @public * * @param {Object} [options] */ voicingSpeakHintResponse( options ) { // options are passed along to collectAndSpeakResponse, see that function for additional options options = merge( { hintResponse: this._voicingHintResponse }, options ); this.collectAndSpeakResponse( options ); }, /** * Collect responses with the voicingManager and speak the output with an UtteranceQueue. * @protected * * @param {Object} [options] */ collectAndSpeakResponse( options ) { options = merge( { // {boolean} - whether or not this response should ignore the Properties of voicingManager ignoreProperties: this._ignoreVoicingManagerProperties, // {Object} - collection of string patterns to use with voicingManager.collectResponses, see // VoicingResponsePatterns for more information. responsePatterns: this._voicingResponsePatterns, // {Utterance|null} - The utterance to use if you want this response to be more controlled in the // UtteranceQueue. utterance: null }, options ); const response = voicingManager.collectResponses( options ); if ( options.utterance ) { options.utterance.alert = response; this.speakContent( options.utterance ); } else { this.speakContent( response ); } }, /** * Use the provided function to create content to speak in response to Input. The content then added to the * back of the voicing utterance queue. * @protected * * @param {null|AlertableDef} content */ speakContent( content ) { // don't send to utteranceQueue if response is empty if ( content ) { const utteranceQueue = this.utteranceQueue || voicingUtteranceQueue; utteranceQueue.addToBack( content ); } }, /** * Sets the voicingNameResponse for this Node. This is usually the label of the element and is spoken * when the object receives input. When requesting speech, this will only be spoken if * voicingManager.namesProperty is set to true. * * @public * * @param {string|null} response */ setVoicingNameResponse( response ) { this._voicingNameResponse = response; }, set voicingNameResponse( response ) { this.setVoicingNameResponse( response ); }, /** * Get the voicingNameResponse for this Node. * @public * * @returns {string|null} */ getVoicingNameResponse() { return this._voicingNameResponse; }, get voicingNameResponse() { return this.getVoicingNameResponse(); }, /** * Set the object response for this Node. This is usually the state information associated with this Node, such * as its current input value. When requesting speech, this will only be heard when * voicingManager.objectChangesProperty is set to true. * @public * * @param {string|null} response */ setVoicingObjectResponse( response ) { this._voicingObjectResponse = response; }, set voicingObjectResponse( response ) { this.setVoicingObjectResponse( response ); }, /** * Gets the object response for this Node. * @public * * @returns {string} */ getVoicingObjectResponse() { return this._voicingObjectResponse; }, get voicingObjectResponse() { return this.getVoicingObjectResponse(); }, /** * Set the context response for this Node. This is usually the content that describes what has happened in * the surrounding application in response to interaction with this Node. When requesting speech, this will * only be heard if voicingManager.contextChangesProperty is set to true. * @public * * @param {string|null} response */ setVoicingContextResponse( response ) { this._voicingContextResponse = response; }, set voicingContextResponse( response ) { this.setVoicingContextResponse( response ); }, /** * Gets the context response for this Node. * @public * * @returns {string|null} */ getVoicingContextResponse() { return this._voicingContextResponse; }, get voicingContextResponse() { return this.getVoicingContextResponse(); }, /** * Sets the hint response for this Node. This is usually a response that describes how to interact with this Node. * When requesting speech, this will only be spoken when voicingManager.hintsProperty is set to true. * @public * * @param {string|null} response */ setVoicingHintResponse( response ) { this._voicingHintResponse = response; }, set voicingHintResponse( response ) { this.setVoicingHintResponse( response ); }, /** * Gets the hint response for this Node. * @public * * @returns {string|null} */ getVoicingHintResponse() { return this._voicingHintResponse; }, get voicingHintResponse() { return this.getVoicingHintResponse(); }, /** * Set whether or not all responses for this Node will ignore the Properties of voicingManager. If false, * all responses will be spoken regardless of voicingManager Properties, which are generally set in user * preferences. * @public */ setVoicingIgnoreVoicingManagerProperties( ignoreProperties ) { this._voicingIgnoreVoicingManagerProperties = ignoreProperties; }, set voicingIgnoreVoicingManagerProperties( ignoreProperties ) { this.setVoicingIgnoreVoicingManagerProperties( ignoreProperties ); }, /** * Get whether or not responses are ignoring voicingManager Properties. */ getVoicingIgnoreVoicingManagerProperties() { return this._voicingIgnoreVoicingManagerProperties; }, get voicingIgnoreVoicingManagerProperties() { return this.getVoicingIgnoreVoicingManagerProperties(); }, /** * Sets the collection of patterns to use for voicing responses, controlling the order, punctuation, and * additional content for each combination of response. See VoicingResponsePatterns.js if you wish to use * a collection of string patterns that are not the default. * @public * * @param {Object} patterns - see VoicingResponsePatterns */ setVoicingResponsePatterns( patterns ) { this._voicingResponsePatterns = patterns; }, set voicingResponsePatterns( patterns ) { this.setVoicingResponsePatterns( patterns ); }, /** * Get the VoicingResponsePatterns object that this Voicing Node is using to collect responses. * @public * * @returns {Object} */ getVoicingResponsePatterns() { return this._voicingResponsePatterns; }, get voicingResponsePatterns() { return this.getVoicingResponsePatterns(); }, /** * Sets the utteranceQueue through which voicing associated with this Node will be spoken. By default, * the Display's voicingUtteranceQueue is used. But you can specify a different one if more complicated * management of voicing is necessary. * @public * * @param {UtteranceQueue} utteranceQueue */ setVoicingUtteranceQueue( utteranceQueue ) { this._voicingUtteranceQueue = utteranceQueue; }, set utteranceQueue( utteranceQueue ) { this.setVoicingUtteranceQueue( utteranceQueue ); }, /** * Gets the utteranceQueue through which voicing associated with this Node will be spoken. * @public * * @returns {UtteranceQueue} */ getUtteranceQueue() { return this._voicingUtteranceQueue; }, get utteranceQueue() { return this.getUtteranceQueue(); }, /** * Detaches references that ensure this components of this Trait are eligible for garbage collection. * @public */ disposeVoicing() { this.removeInputListener( this.speakContentOnFocusListener ); this.disposeMouseHighlighting(); } } ); } }; scenery.register( 'Voicing', Voicing ); export default Voicing;
js/accessibility/voicing/Voicing.js
// Copyright 2021, University of Colorado Boulder /** * A trait for Node that supports the Voicing feature, under accessibility. Allows you to define responses for the Node * and make requests to speak that content using HTML5 SpeechSynthesis and the UtteranceQueue. Voicing content is * organized into four categories which are responsible for describing different things and whose output of content * can be controlled by the voicingManager. These include the * * - "Name" response: The name of the object that uses Voicing. Similar to the "Accessible Name" of PDOM. * - "Object" response: The state information about the object that uses Voicing. * - "Context" response: The contextual changes that result from interaction with the Node that uses Voicing. * - "Hint" response: A supporting hint that guides the user toward a desired interaction. * * See the property and setter documentation for each of these responses for more information. * * Once this content is set, you can make a request to speak it using an UtteranceQueue with one of the provided * functions of Voicing. It is up to you to call one of these functions when you wish for speech to be made. The only * exception is on the 'focus', which consistently speaks content for all Nodes that are composed with Voicing. * * @author Jesse Greenberg (PhET Interactive Simulations) */ import extend from '../../../../phet-core/js/extend.js'; import inheritance from '../../../../phet-core/js/inheritance.js'; import merge from '../../../../phet-core/js/merge.js'; import Node from '../../nodes/Node.js'; import scenery from '../../scenery.js'; import MouseHighlighting from './MouseHighlighting.js'; import voicingManager from './voicingManager.js'; import VoicingResponsePatterns from './VoicingResponsePatterns.js'; import voicingUtteranceQueue from './voicingUtteranceQueue.js'; // options that are supported by Voicing.js. Added to mutator keys so that Voicing properties can be set with mutate. const VOICING_OPTION_KEYS = [ 'voicingNameResponse', 'voicingObjectResponse', 'voicingContextResponse', 'voicingHintResponse', 'voicingUtteranceQueue' ]; const Voicing = { compose( type ) { assert && assert( _.includes( inheritance( type ), Node ), 'Only Node subtypes should compose Voicing' ); const proto = type.prototype; // compose with mouse highlighting MouseHighlighting.compose( type ); extend( proto, { /** * {Array.<string>} - String keys for all of the allowed options that will be set by node.mutate( options ), in * the order they will be evaluated. * @protected * * NOTE: See Node's _mutatorKeys documentation for more information on how this operates, and potential special * cases that may apply. */ _mutatorKeys: VOICING_OPTION_KEYS.concat( proto._mutatorKeys ), /** * Initialize in the type being composed with Voicing. Call this in the constructor. * @param {Object} [options] - NOTE: much of the time, the Node this composes into will call mutate for you, be careful not to double call. * @public */ initializeVoicing( options ) { assert && assert( this.voicing === undefined, 'Voicing has already been initialized for this Node' ); // initialize "super" Trait to support highlights on mouse input this.initializeMouseHighlighting(); // @public (read-only, scenery-internal) - flag indicating that this Node is composed with Voicing functionality this.voicing = true; // @private {string|null} - The response to be spoken for this Node when speaking names. This is usually // the accessible name for the Node, typically spoken on focus and on interaction, labelling what the object is. this._voicingNameResponse = null; // @private {string|null} - The response to be spoken for this node when speaking about object changes. This // is usually the state information directly associated with this Node, such as its current input value. this._voicingObjectResponse = null; // @private {string|null} - The response to be spoken for this node when speaking about context changes. // This is usually a response that describes the surrounding changes that have occurred after interacting // with the object. this._voicingContextResponse = null; // @private {string|null} - The response to be spoken when speaking hints. This is usually the response // that guides the user toward further interaction with this object if it is important to do so to use // the application. this._voicingHintResponse = null; // @private {boolean} - Controls whether or not object, context, and hint responses are controlled // by voicingManager Properties. If true, all responses will be spoken when requested, regardless // of these Properties. This is often useful for surrounding UI components where it is important // that information be heard even when certain responses have been disabled. this._voicingIgnoreVoicingManagerProperties = false; // @private {UtteranceQueue} - The utteranceQueue that responses for this Node will be spoken through. // By default, it will go through the singleton voicingUtteranceQueue, but you may need separate // UtteranceQueues for different areas of content in your application. For example, Voicing and // the default voicingUtteranceQueue may be disabled, but you could still want some speech to come through // while user is changing preferences or other settings. this._voicingUtteranceQueue = null; // {Object} - A collection of response patterns that are used to collect the responses of this Voicing Node // with voicingManager. Controls the order of the Voicing responses and even punctuation used when responses // are assembled into final content for the UtteranceQueue. See VoicingResponsePatterns for more details. this._voicingResponsePatterns = VoicingResponsePatterns.DEFAULT_RESPONSE_PATTERNS; // @private {Object} - Input listener that speaks content on focus. This is the only input listener added // by Voicing, but it is the one that is consistent for all Voicing nodes. On focus, speak the name, object // response, and interaction hint. this.speakContentOnFocusListener = { focus: event => { this.voicingSpeakFullResponse( { contextResponse: null } ); } }; this.addInputListener( this.speakContentOnFocusListener ); // support passing options through directly on initialize if ( options ) { this.mutate( _.pick( options, VOICING_OPTION_KEYS ) ); } }, /** * Speak all responses assigned to this Node. Options allow you to override a responses for this particular * speech request. Each response is only spoken if the associated Property of voicingManager is true. If * all are Properties are false, nothing will be spoken. * @public * * @param {Object} [options] */ voicingSpeakFullResponse( options ) { // options are passed along to collectAndSpeakResponse, see that function for additional options options = merge( { nameResponse: this._voicingNameResponse, objectResponse: this._voicingObjectResponse, contextResponse: this._voicingContextResponse, hintResponse: this._voicingHintResponse }, options ); this.collectAndSpeakResponse( options ); }, /** * Speak ONLY the provided responses that you pass in with options. This will NOT speak the name, object, * context, or hint responses assigned to this node by default. But it allows for clarity at usages so it is * clear that you are only requesting certain responses. If you want to speak all of the responses assigned * to this Node, use voicingSpeakFullResponse(). * * Each response will only be spoken if the Properties of voicingManager are true. If all of those are false, * nothing will be spoken. * @public * * @param {Object} [options] */ voicingSpeakResponse( options ) { // options are passed along to collectAndSpeakResponse, see that function for additional options options = merge( { nameResponse: null, objectResponse: null, contextResponse: null, hintResponse: null }, options ); this.collectAndSpeakResponse( options ); }, /** * Speak only the name response assigned to this Node. * @param options */ voicingSpeakNameResponse( options ) { // options are passed along to collectAndSpeakResponse, see that function for additional options options = merge( { nameResponse: this._voicingNameResponse }, options ); this.collectAndSpeakResponse( options ); }, /** * Speak only the object response assigned to this Node. * @public * * @param {Object} [options] */ voicingSpeakObjectResponse( options ) { // options are passed along to collectAndSpeakResponse, see that function for additional options options = merge( { objectResponse: this._voicingObjectResponse }, options ); this.collectAndSpeakResponse( options ); }, /** * Speak only the context response assigned to this Node. * @public * * @param {Object} [options] */ voicingSpeakContextResponse( options ) { // options are passed along to collectAndSpeakResponse, see that function for additional options options = merge( { contextResponse: this._voicingContextResponse }, options ); this.collectAndSpeakResponse( options ); }, /** * Speak only the hint response assigned to this Node. * @public * * @param {Object} [options] */ voicingSpeakHintResponse( options ) { // options are passed along to collectAndSpeakResponse, see that function for additional options options = merge( { hintResponse: this._voicingHintResponse }, options ); this.collectAndSpeakResponse( options ); }, /** * Collect responses with the voicingManager and speak the output with an UtteranceQueue. * @protected * * @param {Object} [options] */ collectAndSpeakResponse( options ) { options = merge( { // {boolean} - whether or not this response should ignore the Properties of voicingManager ignoreProperties: this._ignoreVoicingManagerProperties, // {Object} - collection of string patterns to use with voicingManager.collectResponses, see // VoicingResponsePatterns for more information. responsePatterns: this._voicingResponsePatterns, // {Utterance|null} - The utterance to use if you want this response to be more controlled in the // UtteranceQueue. utterance: null }, options ); const response = voicingManager.collectResponses( options ); if ( options.utterance ) { options.utterance.alert = response; this.speakContent( options.utterance ); } else { this.speakContent( response ); } }, /** * Use the provided function to create content to speak in response to Input. The content then added to the * back of the voicing utterance queue. * @protected * * @param {null|AlertableDef} content */ speakContent( content ) { // don't send to utteranceQueue if response is empty if ( content ) { const utteranceQueue = this.utteranceQueue || voicingUtteranceQueue; utteranceQueue.addToBack( content ); } }, /** * Sets the voicingNameResponse for this Node. This is usually the label of the element and is spoken * when the object receives input. When requesting speech, this will only be spoken if * voicingManager.namesProperty is set to true. * * @public * * @param {string|null} response */ setVoicingNameResponse( response ) { this._voicingNameResponse = response; }, set voicingNameResponse( response ) { this.setVoicingNameResponse( response ); }, /** * Get the voicingNameResponse for this Node. * @public * * @returns {string|null} */ getVoicingNameResponse() { return this._voicingNameResponse; }, get voicingNameResponse() { return this.getVoicingNameResponse(); }, /** * Set the object response for this Node. This is usually the state information associated with this Node, such * as its current input value. When requesting speech, this will only be heard when * voicingManager.objectChangesProperty is set to true. * @public * * @param {string|null} response */ setVoicingObjectResponse( response ) { this._voicingObjectResponse = response; }, set voicingObjectResponse( response ) { this.setVoicingObjectResponse( response ); }, /** * Gets the object response for this Node. * @public * * @returns {string} */ getVoicingObjectResponse() { return this._voicingObjectResponse; }, get voicingObjectResponse() { return this.getVoicingObjectResponse(); }, /** * Set the context response for this Node. This is usually the content that describes what has happened in * the surrounding application in response to interaction with this Node. When requesting speech, this will * only be heard if voicingManager.contextChangesProperty is set to true. * @public * * @param {string|null} response */ setVoicingContextResponse( response ) { this._voicingContextResponse = response; }, set voicingContextResponse( response ) { this.setVoicingContextResponse( response ); }, /** * Gets the context response for this Node. * @public * * @returns {string|null} */ getVoicingContextResponse() { return this._voicingContextResponse; }, get voicingContextResponse() { return this.getVoicingContextResponse(); }, /** * Sets the hint response for this Node. This is usually a response that describes how to interact with this Node. * When requesting speech, this will only be spoken when voicingManager.hintsProperty is set to true. * @public * * @param {string|null} response */ setVoicingHintResponse( response ) { this._voicingHintResponse = response; }, set voicingHintResponse( response ) { this.setVoicingHintResponse( response ); }, /** * Gets the hint response for this Node. * @public * * @returns {string|null} */ getVoicingHintResponse() { return this._voicingHintResponse; }, get voicingHintResponse() { return this.getVoicingHintResponse(); }, /** * Set whether or not all responses for this Node will ignore the Properties of voicingManager. If false, * all responses will be spoken regardless of voicingManager Properties, which are generally set in user * preferences. * @public */ setVoicingIgnoreVoicingManagerProperties( ignoreProperties ) { this._voicingIgnoreVoicingManagerProperties = ignoreProperties; }, set voicingIgnoreVoicingManagerProperties( ignoreProperties ) { this.setVoicingIgnoreVoicingManagerProperties( ignoreProperties ); }, /** * Get whether or not responses are ignoring voicingManager Properties. */ getVoicingIgnoreVoicingManagerProperties() { return this._voicingIgnoreVoicingManagerProperties; }, get voicingIgnoreVoicingManagerProperties() { return this.getVoicingIgnoreVoicingManagerProperties(); }, /** * Sets the collection of patterns to use for voicing responses, controlling the order, punctuation, and * additional content for each combination of response. See VoicingResponsePatterns.js if you wish to use * a collection of string patterns that are not the default. * @public * * @param {Object} patterns - see VoicingResponsePatterns */ setVoicingResponsePatterns( patterns ) { this._voicingResponsePatterns = patterns; }, set voicingResponsePatterns( patterns ) { this.setVoicingResponsePatterns( patterns ); }, /** * Get the VoicingResponsePatterns object that this Voicing Node is using to collect responses. * @public * * @returns {Object} */ getVoicingResponsePatterns() { return this._voicingResponsePatterns; }, get voicingResponsePatterns() { return this.getVoicingResponsePatterns(); }, /** * Sets the utteranceQueue through which voicing associated with this Node will be spoken. By default, * the Display's voicingUtteranceQueue is used. But you can specify a different one if more complicated * management of voicing is necessary. * @public * * @param {UtteranceQueue} utteranceQueue */ setVoicingUtteranceQueue( utteranceQueue ) { this._voicingUtteranceQueue = utteranceQueue; }, set utteranceQueue( utteranceQueue ) { this.setVoicingUtteranceQueue( utteranceQueue ); }, /** * Gets the utteranceQueue through which voicing associated with this Node will be spoken. * @public * * @returns {UtteranceQueue} */ getUtteranceQueue() { return this._voicingUtteranceQueue; }, get utteranceQueue() { return this.getUtteranceQueue(); }, /** * Detaches references that ensure this components of this Trait are eligible for garbage collection. * @public */ disposeVoicing() { this.removeInputListener( this.speakContentOnFocusListener ); this.disposeMouseHighlighting(); } } ); } }; scenery.register( 'Voicing', Voicing ); export default Voicing;
More documentation improvements
js/accessibility/voicing/Voicing.js
More documentation improvements
<ide><path>s/accessibility/voicing/Voicing.js <ide> /** <ide> * A trait for Node that supports the Voicing feature, under accessibility. Allows you to define responses for the Node <ide> * and make requests to speak that content using HTML5 SpeechSynthesis and the UtteranceQueue. Voicing content is <del> * organized into four categories which are responsible for describing different things and whose output of content <add> * organized into four categories which are responsible for describing different things. Output of this content <ide> * can be controlled by the voicingManager. These include the <ide> * <del> * - "Name" response: The name of the object that uses Voicing. Similar to the "Accessible Name" of PDOM. <add> * - "Name" response: The name of the object that uses Voicing. Similar to the "Accessible Name" in web accessibility. <ide> * - "Object" response: The state information about the object that uses Voicing. <ide> * - "Context" response: The contextual changes that result from interaction with the Node that uses Voicing. <del> * - "Hint" response: A supporting hint that guides the user toward a desired interaction. <add> * - "Hint" response: A supporting hint that guides the user toward a desired interaction with this Node. <ide> * <ide> * See the property and setter documentation for each of these responses for more information. <ide> * <ide> * Once this content is set, you can make a request to speak it using an UtteranceQueue with one of the provided <del> * functions of Voicing. It is up to you to call one of these functions when you wish for speech to be made. The only <del> * exception is on the 'focus', which consistently speaks content for all Nodes that are composed with Voicing. <add> * functions in this Trait. It is up to you to call one of these functions when you wish for speech to be made. The only <add> * exception is on the 'focus' event. Every Node that composes Voicing will speak its responses by when it <add> * receives focus. <ide> * <ide> * @author Jesse Greenberg (PhET Interactive Simulations) <ide> */
JavaScript
mit
8495d6ec643cfec0fd78e471e264bc177a230c46
0
egovernment/eregistrations,egovernment/eregistrations,egovernment/eregistrations
'use strict'; var db = require('mano').db, user = db.User.prototype, Set = require('es6-set'), filterOfficial = require('../../model/filter-official-roles'); exports['sub-main'] = function () { section( { class: 'content' }, form( fieldset( { class: 'section-primary' }, h3("Edit user"), hr(), ul({ class: 'form-elements fieldset' }, li(field({ dbjs: user._firstName })), li(field({ dbjs: user._lastName })), li(field({ dbjs: user._roles, multiple: false, only: new Set(['users-admin', 'meta-admin', 'demo-user', 'user']), append: option({ value: 'official' }, "Official") } ) ), li(field({ dbjs: user._roles, filter: filterOfficial, label: 'Officials' } ) ), li(field({ dbjs: user._email })), li(field({ dbjs: user._password })) ), p( { class: 'submit-placeholder' }, input( { type: 'submit' }, "Save" ) ) ) ) ); };
view/prototype/edit-user.js
'use strict'; var db = require('mano').db, user = db.User.prototype, Set = require('es6-set'), filterOfficial = require('../../model/filter-official-roles'); exports['sub-main'] = function () { section( form( { class: 'content' }, fieldset( h3("Edit user"), hr(), ul({ class: 'form-elements fieldset' }, li(field({ dbjs: user._firstName })), li(field({ dbjs: user._lastName })), li(field({ dbjs: user._roles, multiple: false, only: new Set(['users-admin', 'meta-admin', 'demo-user', 'user']), append: option({ value: 'official' }, "Official") } ) ), li(field({ dbjs: user._roles, filter: filterOfficial, label: 'Officials' } ) ), li(field({ dbjs: user._email })), li(field({ dbjs: user._password })) ), p( { class: 'submit-placeholder' }, input( { type: 'submit' }, "Save" ) ) ) ) ); };
Users-admin edit-user page refactor based on section-primary. #114
view/prototype/edit-user.js
Users-admin edit-user page refactor based on section-primary. #114
<ide><path>iew/prototype/edit-user.js <ide> <ide> exports['sub-main'] = function () { <ide> section( <add> { class: 'content' }, <ide> form( <del> { class: 'content' }, <ide> fieldset( <add> { class: 'section-primary' }, <ide> h3("Edit user"), <ide> hr(), <ide> ul({ class: 'form-elements fieldset' },
JavaScript
mit
6ddbce017181aac378947000f94d4a8f2bedd778
0
php-ug/slack-irc,erikdesjardins/slack-irc,leeopop/slack-irc,chipx86/slack-irc,reactiflux/discord-irc,tcr/slack-irc,umegaya/slack-irc,ekmartin/slack-irc,zabirauf/slack-irc,robertkety/slack-irc,andreaja/slack-irc,mxm/slack-irc,xbmc/slack-irc,lmtierney/slack-irc
var request = require('supertest'); var chai = require('chai'); var sinonChai = require('sinon-chai'); var sinon = require('sinon'); var irc = require('irc'); chai.use(sinonChai); chai.should(); describe('/send', function() { var app; var channelMapping = { '#slack': '#irc' }; var addListenerStub = sinon.stub(); var sayStub = sinon.stub(); before(function() { function clientStub() {} clientStub.prototype.addListener = addListenerStub; clientStub.prototype.say = sayStub; irc.Client = clientStub; process.env.OUTGOING_HOOK_TOKEN = 'test'; process.env.CHANNEL_MAPPING = JSON.stringify(channelMapping); app = require('../lib/server'); }); afterEach(function() { sayStub.reset(); addListenerStub.reset(); }); it('should return 403 for invalid tokens', function(done) { request(app) .post('/send') .send('token=badtoken') .expect(403) .expect('Content-Type', /json/) .end(function(err, res) { if (err) return done(err); var error = res.body; error.text.should.equal('Invalid hook token received'); error.status.should.equal(403); sayStub.should.not.have.been.called; done(); }); }); it('should return 200 for messages from slackbot', function(done) { var bodyParts = [ 'token=' + process.env.OUTGOING_HOOK_TOKEN, 'user_id=USLACKBOT', ]; var body = bodyParts.join('&'); request(app) .post('/send') .send(body) .expect(200) .end(function(err, res) { if (err) return done(err); sayStub.should.not.have.been.called; done(); }); }); it('should try to send an irc message', function(done) { var channel = 'slack'; var username = 'testuser'; var message = 'hi'; var bodyParts = [ 'token=' + process.env.OUTGOING_HOOK_TOKEN, 'channel_name=' + channel, 'user_name=' + username, 'text=' + message ]; var body = bodyParts.join('&'); request(app) .post('/send') .send(body) .expect(202) .end(function(err, res) { if (err) return done(err); var ircChannel = channelMapping['#' + channel]; sayStub.should.have.been.calledOnce; sayStub.should.have.been.calledWithExactly(ircChannel, username + ': ' + message); done(); }); }); });
test/api.test.js
var request = require('supertest'); var chai = require('chai'); var sinonChai = require('sinon-chai'); var sinon = require('sinon'); var irc = require('irc'); chai.use(sinonChai); chai.should(); describe('/send', function() { var app; var channelMapping = { '#slack': '#irc' }; var addListenerStub = sinon.stub(); var sayStub = sinon.stub(); before(function() { function clientStub() {} clientStub.prototype.addListener = addListenerStub; clientStub.prototype.say = sayStub; irc.Client = clientStub; process.env.OUTGOING_HOOK_TOKEN = 'test'; process.env.CHANNEL_MAPPING = JSON.stringify(channelMapping); app = require('../lib/server'); }); afterEach(function() { sayStub.reset(); addListenerStub.reset(); }); it('should return 403 for invalid tokens', function(done) { request(app) .post('/send') .send('token=badtoken') .expect(403) .expect('Content-Type', /json/) .end(function(err, res) { if (err) return done(err); var error = res.body; error.text.should.equal('Invalid hook token received'); error.status.should.equal(403); sayStub.should.not.have.been.called; done(); }); }); it('should try to send an irc message', function(done) { var channel = 'slack'; var username = 'testuser'; var message = 'hi'; var bodyParts = [ 'token=' + process.env.OUTGOING_HOOK_TOKEN, 'channel_name=' + channel, 'user_name=' + username, 'text=' + message ]; var body = bodyParts.join('&'); request(app) .post('/send') .send(body) .expect(202) .end(function(err, res) { if (err) return done(err); var ircChannel = channelMapping['#' + channel]; sayStub.should.have.been.calledOnce; sayStub.should.have.been.calledWithExactly(ircChannel, username + ': ' + message); done(); }); }); });
Add a ignoreBot test
test/api.test.js
Add a ignoreBot test
<ide><path>est/api.test.js <ide> }); <ide> }); <ide> <add> it('should return 200 for messages from slackbot', function(done) { <add> var bodyParts = [ <add> 'token=' + process.env.OUTGOING_HOOK_TOKEN, <add> 'user_id=USLACKBOT', <add> ]; <add> var body = bodyParts.join('&'); <add> <add> request(app) <add> .post('/send') <add> .send(body) <add> .expect(200) <add> .end(function(err, res) { <add> if (err) return done(err); <add> sayStub.should.not.have.been.called; <add> done(); <add> }); <add> }); <add> <ide> it('should try to send an irc message', function(done) { <ide> var channel = 'slack'; <ide> var username = 'testuser';
Java
mit
cc27b3f7cfe95501b7f53543225ee983d2e5e206
0
cesarferreira/AndroidQuickUtils,HKMOpen/AndroidQuickUtils,cesarferreira/AndroidQuickUtils,mumer92/AndroidQuickUtils
package quickutils.core.util.math; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.Locale; import java.util.Random; import quickutils.core.QuickUtils; public class math { /** * private constructor */ // private math() { // } private static final float DEG_TO_RAD = 3.1415926f / 180.0f; private static final float RAD_TO_DEG = 180.0f / 3.1415926f; /** * Rounds a double value to a certain number of digits * * @param toBeRounded * number to be rounded * @param digits * number of digits to be rounded * @return the double rounded */ public static double round(double toBeRounded, int digits) { if (digits < 0) { QuickUtils.log.e("must be greater than 0"); return 0; } String formater = ""; for (int i = 0; i < digits; i++) { formater += "#"; } DecimalFormat twoDForm = new DecimalFormat("#." + formater, new DecimalFormatSymbols(Locale.US)); return Double.valueOf(twoDForm.format(toBeRounded)); } /** * Converts pounds to kilograms * * @param weight * to be converted * @return value converted */ public static double poundsToKg(double weight) { return weight / 2.2; } /** * Converts kilograms to pounds * * @param weight * to be converted * @return value converted */ public static double kgToPounds(double weight) { return weight * 2.2; } /** * Converts inches to centimeters * * @param value * to be converted * @return value converted */ public static double inchesToCm(double inches) { return inches * 2.54; } /** * Converts centimeters to inches * * @param value * to be converted * @return value converted */ public static double cmToInches(double cm) { return cm / 2.54; } /** * Returns a random integer between MIN inclusive and MAX inclusive. * * @param min * value inclusive * @param max * value inclusive * @return an int between MIN inclusive and MAX exclusive. */ public static int getRandomInteger(int min, int max) { Random r = new Random(); return r.nextInt(max - min + 1) + min; } /** * Returns a random integer between 0 (Zero) inclusive and MAX inclusive. <br/> * Same as {@code getRandomInteger(0, max);} <br/> * See {@see RandomUtil#getRandomInteger(int, int)} * * @param max * value exclusive * @return an int between 0 inclusive and MAX inclusive. */ public static int getRandomInteger(int max) { return getRandomInteger(0, max); } /** * Returns a random double between MIN inclusive and MAX inclusive. * * @param min * value inclusive * @param max * value inclusive * @return an int between 0 inclusive and MAX exclusive. */ public static double getRandomDouble(double min, double max) { Random r = new Random(); return min + (max - min) * r.nextDouble(); } /** * Returns a random double between 0 (Zero) inclusive and MAX inclusive. <br/> * Same as {@code getRandomDouble(0, max);} <br/> * See {@see RandomUtil#getRandomDouble(double, double)} * * @param max * value exclusive * @return an int between 0 inclusive and MAX inclusive. */ public static double getRandomDouble(double max) { return getRandomDouble(0, max); } /** * Get a random position(object) from an array of generic objects. <br/> * Using generics saves the trouble of casting the return object. * * @param <T> * the type of the array to get the object from * @param array * the array with objects * @return random object from given array or null of array is either null or * empty */ public static <T> T getRandomPosition(T[] array) { if (array == null || array.length == 0) { return null; } return array[getRandomInteger(array.length - 1)]; } /** * Get a random position(object) from a list of generic objects. <br/> * Using generics saves the trouble of casting the return object. * * @param <T> * the type of the list objects to get the object from * @param list * the list with objects * @return random object from given list or null of list is either null or * empty */ public static <T> T getRandomPosition(List<T> list) { if (list == null || list.isEmpty()) { return null; } return list.get(getRandomInteger(list.size() - 1)); } /** * Degrees to radians * * @param degrees * @return the converted value */ public static float degreesToRadians(float degrees) { return degrees * DEG_TO_RAD; } /** * Radians to degrees * * @param degrees * @return the converted value */ public static float radiansToDegrees(float radians) { return radians * RAD_TO_DEG; } /** * Arc cosine * * @param value * @return Returns the closest double approximation of the arc cosine of the * argument within the range [0..pi]. The returned result is within * 1 ulp (unit in the last place) of the real result. */ public static float acos(float value) { return (float) Math.acos(value); } /** * Arc sine * * @param value * @return Returns the closest double approximation of the arc sine of the * argument within the range [-pi/2..pi/2]. The returned result is * within 1 ulp (unit in the last place) of the real result. */ public static float asin(float value) { return (float) Math.asin(value); } /** * Arc tangent * * @param value * @return Returns the closest double approximation of the arc tangent of * the argument within the range [-pi/2..pi/2]. The returned result * is within 1 ulp (unit in the last place) of the real result. */ public static float atan(float value) { return (float) Math.atan(value); } /** * Arc tangent of y/x within the range [-pi..pi] * * @param a * @param b * @return Returns the closest double approximation of the arc tangent of * y/x within the range [-pi..pi]. This is the angle of the polar * representation of the rectangular coordinates (x,y). The returned * result is within 2 ulps (units in the last place) of the real * result. */ public static float atan2(float a, float b) { return (float) Math.atan2(a, b); } /** * Tangent of an angle * * @param angle * angle * @return the tangent */ public static float tan(float angle) { return (float) Math.tan(angle); } /** * Absolute value * * @param v * value * @return returns the absolute value */ public static float abs(float v) { return v > 0 ? v : -v; } /** * Number's logarithm <br> * Special cases: * * <li>log(+0.0) = -infinity</li> <li>log(-0.0) = -infinity</li><li> * log((anything < 0) = NaN</li> <li>log(+infinity) = +infinity</li><li> * log(-infinity) = NaN</li><li>log(NaN) = NaN</li> * * * @param number * @return Returns the closest double approximation of the natural logarithm * of the argument. The returned result is within 1 ulp (unit in the * last place) of the real result. */ public static float logarithm(float number) { return (float) Math.log(number); } /** * Number's Exponencial * * @param number * float number * @return Returns the closest double approximation of the natural logarithm * of the argument. The returned result is within 1 ulp (unit in the * last place) of the real result. */ public static float exponencial(float number) { return (float) Math.exp(number); } /** * Gets the higher number * * @param a * float number * @param b * float number * @return the higher number between a and b */ public static float max(float a, float b) { return a > b ? a : b; } /** * Gets the higher number * * @param a * int number * @param b * int number * @return the higher number between a and b */ public static int max(int a, int b) { return a > b ? a : b; } /** * Gets the lower number * * @param a * float number * @param b * float number * @return the lower number between a and b */ public static float min(float a, float b) { return a < b ? a : b; } /** * Gets the lower number * * @param a * float number * @param b * float number * @return the lower number between a and b */ public static int min(int a, int b) { return a < b ? a : b; } /** * Check if a number is Odd * * @param num * int number * @return true if the num is odd and false if it's even */ public static boolean isOdd(int num) { return !isEven(num); } /** * Check if a number is Even * * @param num * int number * @return true if the num is even and false if it's odd */ public static boolean isEven(int num) { return (num % 2 == 0); } /** * Returns a random number between MIN inclusive and MAX exclusive. * * @param min * value inclusive * @param max * value exclusive * @return an int between MIN inclusive and MAX exclusive. */ public static int getRandomNumber(int min, int max) { Random r = new Random(); return r.nextInt(max - min + 1) + min; } /** * Truncates a value * @param value - value to be truncated * @param places - decimal places * @return */ public static double truncate(double value, int places) { if (places < 0) { throw new IllegalArgumentException(); } long factor = (long) Math.pow(10, places); value = value * factor; long tmp = (long) value; return (double) tmp / factor; } }
quickutils/src/quickutils/core/util/math/math.java
package quickutils.core.util.math; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.Locale; import java.util.Random; import quickutils.core.QuickUtils; public class math { /** * private constructor */ // private math() { // } private static final float DEG_TO_RAD = 3.1415926f / 180.0f; private static final float RAD_TO_DEG = 180.0f / 3.1415926f; /** * Rounds a double value to a certain number of digits * * @param toBeRounded * number to be rounded * @param digits * number of digits to be rounded * @return the double rounded */ public static double round(double toBeRounded, int digits) { if (digits < 0) { QuickUtils.log.e("must be greater than 0"); return 0; } String formater = ""; for (int i = 0; i < digits; i++) { formater += "#"; } DecimalFormat twoDForm = new DecimalFormat("#." + formater, new DecimalFormatSymbols(Locale.US)); return Double.valueOf(twoDForm.format(toBeRounded)); } /** * Converts pounds to kilograms * * @param weight * to be converted * @return value converted */ public static double poundsToKg(double weight) { return weight / 2.2; } /** * Converts kilograms to pounds * * @param weight * to be converted * @return value converted */ public static double kgToPounds(double weight) { return weight * 2.2; } /** * Converts inches to centimeters * * @param value * to be converted * @return value converted */ public static double inchesToCm(double inches) { return inches * 2.54; } /** * Converts centimeters to inches * * @param value * to be converted * @return value converted */ public static double cmToInches(double cm) { return cm / 2.54; } /** * Returns a random integer between MIN inclusive and MAX inclusive. * * @param min * value inclusive * @param max * value inclusive * @return an int between MIN inclusive and MAX exclusive. */ public static int getRandomInteger(int min, int max) { Random r = new Random(); return r.nextInt(max - min + 1) + min; } /** * Returns a random integer between 0 (Zero) inclusive and MAX inclusive. <br/> * Same as {@code getRandomInteger(0, max);} <br/> * See {@see RandomUtil#getRandomInteger(int, int)} * * @param max * value exclusive * @return an int between 0 inclusive and MAX inclusive. */ public static int getRandomInteger(int max) { return getRandomInteger(0, max); } /** * Returns a random double between MIN inclusive and MAX inclusive. * * @param min * value inclusive * @param max * value inclusive * @return an int between 0 inclusive and MAX exclusive. */ public static double getRandomDouble(double min, double max) { Random r = new Random(); return min + (max - min) * r.nextDouble(); } /** * Returns a random double between 0 (Zero) inclusive and MAX inclusive. <br/> * Same as {@code getRandomDouble(0, max);} <br/> * See {@see RandomUtil#getRandomDouble(double, double)} * * @param max * value exclusive * @return an int between 0 inclusive and MAX inclusive. */ public static double getRandomDouble(double max) { return getRandomDouble(0, max); } /** * Get a random position(object) from an array of generic objects. <br/> * Using generics saves the trouble of casting the return object. * * @param <T> * the type of the array to get the object from * @param array * the array with objects * @return random object from given array or null of array is either null or * empty */ public static <T> T getRandomPosition(T[] array) { if (array == null || array.length == 0) { return null; } return array[getRandomInteger(array.length - 1)]; } /** * Get a random position(object) from a list of generic objects. <br/> * Using generics saves the trouble of casting the return object. * * @param <T> * the type of the list objects to get the object from * @param list * the list with objects * @return random object from given list or null of list is either null or * empty */ public static <T> T getRandomPosition(List<T> list) { if (list == null || list.isEmpty()) { return null; } return list.get(getRandomInteger(list.size() - 1)); } /** * Degrees to radians * * @param degrees * @return the converted value */ public static float degreesToRadians(float degrees) { return degrees * DEG_TO_RAD; } /** * Radians to degrees * * @param degrees * @return the converted value */ public static float radiansToDegrees(float radians) { return radians * RAD_TO_DEG; } /** * Arc cosine * * @param value * @return Returns the closest double approximation of the arc cosine of the * argument within the range [0..pi]. The returned result is within * 1 ulp (unit in the last place) of the real result. */ public static float acos(float value) { return (float) Math.acos(value); } /** * Arc sine * * @param value * @return Returns the closest double approximation of the arc sine of the * argument within the range [-pi/2..pi/2]. The returned result is * within 1 ulp (unit in the last place) of the real result. */ public static float asin(float value) { return (float) Math.asin(value); } /** * Arc tangent * * @param value * @return Returns the closest double approximation of the arc tangent of * the argument within the range [-pi/2..pi/2]. The returned result * is within 1 ulp (unit in the last place) of the real result. */ public static float atan(float value) { return (float) Math.atan(value); } /** * Arc tangent of y/x within the range [-pi..pi] * * @param a * @param b * @return Returns the closest double approximation of the arc tangent of * y/x within the range [-pi..pi]. This is the angle of the polar * representation of the rectangular coordinates (x,y). The returned * result is within 2 ulps (units in the last place) of the real * result. */ public static float atan2(float a, float b) { return (float) Math.atan2(a, b); } /** * Tangent of an angle * * @param angle * angle * @return the tangent */ public static float tan(float angle) { return (float) Math.tan(angle); } /** * Absolute value * * @param v * value * @return returns the absolute value */ public static float abs(float v) { return v > 0 ? v : -v; } /** * Number's logarithm <br> * Special cases: * * <li>log(+0.0) = -infinity</li> <li>log(-0.0) = -infinity</li><li> * log((anything < 0) = NaN</li> <li>log(+infinity) = +infinity</li><li> * log(-infinity) = NaN</li><li>log(NaN) = NaN</li> * * * @param number * @return Returns the closest double approximation of the natural logarithm * of the argument. The returned result is within 1 ulp (unit in the * last place) of the real result. */ public static float logarithm(float number) { return (float) Math.log(number); } /** * Number's Exponencial * * @param number * float number * @return Returns the closest double approximation of the natural logarithm * of the argument. The returned result is within 1 ulp (unit in the * last place) of the real result. */ public static float exponencial(float number) { return (float) Math.exp(number); } /** * Gets the higher number * * @param a * float number * @param b * float number * @return the higher number between a and b */ public static float max(float a, float b) { return a > b ? a : b; } /** * Gets the higher number * * @param a * int number * @param b * int number * @return the higher number between a and b */ public static int max(int a, int b) { return a > b ? a : b; } /** * Gets the lower number * * @param a * float number * @param b * float number * @return the lower number between a and b */ public static float min(float a, float b) { return a < b ? a : b; } /** * Gets the lower number * * @param a * float number * @param b * float number * @return the lower number between a and b */ public static int min(int a, int b) { return a < b ? a : b; } /** * Check if a number is Odd * * @param num * int number * @return true if the num is odd and false if it's even */ public static boolean isOdd(int num) { return !isEven(num); } /** * Check if a number is Even * * @param num * int number * @return true if the num is even and false if it's odd */ public static boolean isEven(int num) { return (num % 2 == 0); } /** * Returns a random number between MIN inclusive and MAX exclusive. * * @param min * value inclusive * @param max * value exclusive * @return an int between MIN inclusive and MAX exclusive. */ public static int getRandomNumber(int min, int max) { Random r = new Random(); return r.nextInt(max - min + 1) + min; } }
Truncate added
quickutils/src/quickutils/core/util/math/math.java
Truncate added
<ide><path>uickutils/src/quickutils/core/util/math/math.java <ide> Random r = new Random(); <ide> return r.nextInt(max - min + 1) + min; <ide> } <add> <add> /** <add> * Truncates a value <add> * @param value - value to be truncated <add> * @param places - decimal places <add> * @return <add> */ <add> public static double truncate(double value, int places) { <add> if (places < 0) { <add> throw new IllegalArgumentException(); <add> } <add> <add> long factor = (long) Math.pow(10, places); <add> value = value * factor; <add> long tmp = (long) value; <add> return (double) tmp / factor; <add> } <ide> <ide> }
Java
apache-2.0
56be555733cf0afea1588e0a14da4059d3ebb13d
0
mufaddalq/cloudstack-datera-driver,resmo/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,mufaddalq/cloudstack-datera-driver,wido/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,wido/cloudstack,resmo/cloudstack,wido/cloudstack,resmo/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,mufaddalq/cloudstack-datera-driver,resmo/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,resmo/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,mufaddalq/cloudstack-datera-driver,jcshen007/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,mufaddalq/cloudstack-datera-driver,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,mufaddalq/cloudstack-datera-driver
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cloudstack.engine.rest.service.api; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import org.apache.cloudstack.engine.cloud.entity.api.NetworkEntity; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; @Service("NetworkRestService") @Component @Produces("application/json") public class NetworkRestService { @PUT @Path("/network/create") public NetworkEntity create( @QueryParam("xid") String xid, @QueryParam("display-name") String displayName) { return null; } @GET @Path("/network/{network-id}") public NetworkEntity get(@PathParam("network-id") String networkId) { return null; } @GET @Path("/networks") public List<NetworkEntity> listAll() { return null; } @POST @Path("/network/{network-id}/") public String deploy(@PathParam("network-id") String networkId) { return null; } }
engine/api/src/org/apache/cloudstack/engine/rest/service/api/NetworkRestService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cloudstack.engine.rest.service.api; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import org.apache.cloudstack.engine.cloud.entity.api.NetworkEntity; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; @Service("NetworkRestService") @Component @Produces("application/json") public class NetworkRestService { @PUT @Path("/network/create") public NetworkEntity create( @QueryParam("xid") String xid, @QueryParam("display-name") String displayName) { return null; } @GET @Path("/network/{network-id}") public NetworkEntity get(@PathParam("network-id") String networkId) { return null; } @GET @Path("/networks") public List<NetworkEntity> listAll() { return null; } @POST @Path("/network/{network-id}/") public String deploy(@PathParam("network-id") String networkId) { return null; } }
missing change
engine/api/src/org/apache/cloudstack/engine/rest/service/api/NetworkRestService.java
missing change
<ide><path>ngine/api/src/org/apache/cloudstack/engine/rest/service/api/NetworkRestService.java <ide> public String deploy(@PathParam("network-id") String networkId) { <ide> return null; <ide> } <add> <add> <ide> }
Java
apache-2.0
44420e30251b09f5de054b1d0be5e72bab59fb5c
0
gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas
package uk.ac.ebi.atlas.web.controllers; import org.hibernate.validator.constraints.Range; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; public class Preferences { private static final int DEFAULT_NUMBER_OF_TOP_EXPRESSIONS_TO_BE_HIGHLIGHTED = 10; private static final int DEFAULT_RANKING_SIZE = 100; private static final double DEFAULT_CUTOFF = 0d; @Range(min = 0, max = 1000) private Integer heatmapMatrixSize = DEFAULT_NUMBER_OF_TOP_EXPRESSIONS_TO_BE_HIGHLIGHTED; @NotNull @Range(min = 1, max = 1000) private Integer rankingSize = DEFAULT_RANKING_SIZE; @NotNull @Min(0) private Double cutoff = DEFAULT_CUTOFF; public Integer getHeatmapMatrixSize() { return this.heatmapMatrixSize; } public void setHeatmapMatrixSize(Integer heatmapMatrixSize) { this.heatmapMatrixSize = heatmapMatrixSize; } public Double getCutoff() { return this.cutoff; } public void setCutoff(Double cutoff) { this.cutoff = cutoff; } public Integer getRankingSize() { return this.rankingSize; } public void setRankingSize(Integer rankingSize) { this.rankingSize = rankingSize; } }
web/src/main/java/uk/ac/ebi/atlas/web/controllers/Preferences.java
package uk.ac.ebi.atlas.web.controllers; import org.hibernate.validator.constraints.Range; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; public class Preferences { private static final int DEFAULT_NUMBER_OF_TOP_EXPRESSIONS_TO_BE_HIGHLIGHTED = 3; private static final int DEFAULT_RANKING_SIZE = 100; private static final double DEFAULT_CUTOFF = 0d; @Range(min = 0, max = 1000) private Integer heatmapMatrixSize = DEFAULT_NUMBER_OF_TOP_EXPRESSIONS_TO_BE_HIGHLIGHTED; @NotNull @Range(min = 1, max = 1000) private Integer rankingSize = DEFAULT_RANKING_SIZE; @NotNull @Min(0) private Double cutoff = DEFAULT_CUTOFF; public Integer getHeatmapMatrixSize() { return this.heatmapMatrixSize; } public void setHeatmapMatrixSize(Integer heatmapMatrixSize) { this.heatmapMatrixSize = heatmapMatrixSize; } public Double getCutoff() { return this.cutoff; } public void setCutoff(Double cutoff) { this.cutoff = cutoff; } public Integer getRankingSize() { return this.rankingSize; } public void setRankingSize(Integer rankingSize) { this.rankingSize = rankingSize; } }
increased default heatmapMatrixSize to 10
web/src/main/java/uk/ac/ebi/atlas/web/controllers/Preferences.java
increased default heatmapMatrixSize to 10
<ide><path>eb/src/main/java/uk/ac/ebi/atlas/web/controllers/Preferences.java <ide> <ide> public class Preferences { <ide> <del> private static final int DEFAULT_NUMBER_OF_TOP_EXPRESSIONS_TO_BE_HIGHLIGHTED = 3; <add> private static final int DEFAULT_NUMBER_OF_TOP_EXPRESSIONS_TO_BE_HIGHLIGHTED = 10; <ide> private static final int DEFAULT_RANKING_SIZE = 100; <ide> private static final double DEFAULT_CUTOFF = 0d; <ide>
Java
apache-2.0
4e76a4bd6e27472e487bc3136de3c3439e949302
0
alibaba/canal,zhangwei5095/alibaba-canal,sdgdsffdsfff/canal,alibaba/canal,daniellitoc/canal,alibaba/canal,sdgdsffdsfff/canal,alibaba/canal,zhangwei5095/alibaba-canal,sdgdsffdsfff/canal,gewanbo/canalKafka,alibaba/canal,daniellitoc/canal,gewanbo/canalKafka
package com.alibaba.otter.canal.client.impl.running; import java.net.InetSocketAddress; import java.text.MessageFormat; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.I0Itec.zkclient.IZkDataListener; import org.I0Itec.zkclient.exception.ZkException; import org.I0Itec.zkclient.exception.ZkInterruptedException; import org.I0Itec.zkclient.exception.ZkNoNodeException; import org.I0Itec.zkclient.exception.ZkNodeExistsException; import org.apache.zookeeper.CreateMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import com.alibaba.otter.canal.common.AbstractCanalLifeCycle; import com.alibaba.otter.canal.common.utils.BooleanMutex; import com.alibaba.otter.canal.common.utils.JsonUtils; import com.alibaba.otter.canal.common.zookeeper.ZkClientx; import com.alibaba.otter.canal.common.zookeeper.ZookeeperPathUtils; import com.alibaba.otter.canal.protocol.exception.CanalClientException; /** * clinet running控制 * * @author jianghang 2012-11-22 下午03:43:01 * @version 1.0.0 */ public class ClientRunningMonitor extends AbstractCanalLifeCycle { private static final Logger logger = LoggerFactory.getLogger(ClientRunningMonitor.class); private ZkClientx zkClient; private String destination; private ClientRunningData clientData; private IZkDataListener dataListener; private BooleanMutex mutex = new BooleanMutex(false); private volatile boolean release = false; private volatile ClientRunningData activeData; private ScheduledExecutorService delayExector = Executors.newScheduledThreadPool(1); private ClientRunningListener listener; private int delayTime = 5; public ClientRunningMonitor(){ dataListener = new IZkDataListener() { public void handleDataChange(String dataPath, Object data) throws Exception { MDC.put("destination", destination); ClientRunningData runningData = JsonUtils.unmarshalFromByte((byte[]) data, ClientRunningData.class); if (!isMine(runningData.getAddress())) { mutex.set(false); } if (!runningData.isActive() && isMine(runningData.getAddress())) { // 说明出现了主动释放的操作,并且本机之前是active release = true; releaseRunning();// 彻底释放mainstem } activeData = (ClientRunningData) runningData; } public void handleDataDeleted(String dataPath) throws Exception { MDC.put("destination", destination); mutex.set(false); // 触发一下退出,可能是人为干预的释放操作或者网络闪断引起的session expired timeout processActiveExit(); if (!release && activeData != null && isMine(activeData.getAddress())) { // 如果上一次active的状态就是本机,则即时触发一下active抢占 initRunning(); } else { // 否则就是等待delayTime,避免因网络瞬端或者zk异常,导致出现频繁的切换操作 delayExector.schedule(new Runnable() { public void run() { initRunning(); } }, delayTime, TimeUnit.SECONDS); } } }; } public void start() { super.start(); String path = ZookeeperPathUtils.getDestinationClientRunning(this.destination, clientData.getClientId()); zkClient.subscribeDataChanges(path, dataListener); initRunning(); } public void stop() { super.stop(); String path = ZookeeperPathUtils.getDestinationClientRunning(this.destination, clientData.getClientId()); zkClient.unsubscribeDataChanges(path, dataListener); releaseRunning(); // 尝试一下release } // 改动记录: // 1,在方法上加synchronized关键字,保证同步顺序执行; // 2,判断Zk上已经存在的activeData是否是本机,是的话把mutex重置为true,否则会导致死锁 // 3,增加异常处理,保证出现异常时,running节点能被删除,否则会导致死锁 public synchronized void initRunning() { if (!isStart()) { return; } String path = ZookeeperPathUtils.getDestinationClientRunning(this.destination, clientData.getClientId()); // 序列化 byte[] bytes = JsonUtils.marshalToByte(clientData); try { mutex.set(false); zkClient.create(path, bytes, CreateMode.EPHEMERAL); processActiveEnter();// 触发一下事件 activeData = clientData; mutex.set(true); } catch (ZkNodeExistsException e) { bytes = zkClient.readData(path, true); if (bytes == null) {// 如果不存在节点,立即尝试一次 initRunning(); } else { activeData = JsonUtils.unmarshalFromByte(bytes, ClientRunningData.class); // 如果发现已经存在,判断一下是否自己,避免活锁 if (activeData.getAddress().contains(":") && isMine(activeData.getAddress())) { mutex.set(true); } } } catch (ZkNoNodeException e) { zkClient.createPersistent(ZookeeperPathUtils.getClientIdNodePath(this.destination, clientData.getClientId()), true); // 尝试创建父节点 initRunning(); } catch (Throwable t) { logger.error(MessageFormat.format("There is an error when execute initRunning method, with destination [{0}].", destination), t); // 出现任何异常尝试release releaseRunning(); throw new CanalClientException("something goes wrong in initRunning method. ", t); } } /** * 阻塞等待自己成为active,如果自己成为active,立马返回 * * @throws InterruptedException */ public void waitForActive() throws InterruptedException { initRunning(); mutex.get(); } /** * 检查当前的状态 */ public boolean check() { String path = ZookeeperPathUtils.getDestinationClientRunning(this.destination, clientData.getClientId()); try { byte[] bytes = zkClient.readData(path); ClientRunningData eventData = JsonUtils.unmarshalFromByte(bytes, ClientRunningData.class); activeData = eventData;// 更新下为最新值 // 检查下nid是否为自己 boolean result = isMine(activeData.getAddress()); if (!result) { logger.warn("canal is running in [{}] , but not in [{}]", activeData.getAddress(), clientData.getAddress()); } return result; } catch (ZkNoNodeException e) { logger.warn("canal is not run any in node"); return false; } catch (ZkInterruptedException e) { logger.warn("canal check is interrupt"); Thread.interrupted();// 清除interrupt标记 return check(); } catch (ZkException e) { logger.warn("canal check is failed"); return false; } } public boolean releaseRunning() { if (check()) { String path = ZookeeperPathUtils.getDestinationClientRunning(this.destination, clientData.getClientId()); zkClient.delete(path); mutex.set(false); processActiveExit(); return true; } return false; } // ====================== helper method ====================== private boolean isMine(String address) { return address.equals(clientData.getAddress()); } private void processActiveEnter() { if (listener != null) { // 触发回调,建立与server的socket链接 InetSocketAddress connectAddress = listener.processActiveEnter(); String address = connectAddress.getAddress().getHostAddress() + ":" + connectAddress.getPort(); this.clientData.setAddress(address); String path = ZookeeperPathUtils.getDestinationClientRunning(this.destination, this.clientData.getClientId()); // 序列化 byte[] bytes = JsonUtils.marshalToByte(clientData); zkClient.writeData(path, bytes); } } private void processActiveExit() { if (listener != null) { listener.processActiveExit(); } } public void setListener(ClientRunningListener listener) { this.listener = listener; } // ===================== setter / getter ======================= public void setDestination(String destination) { this.destination = destination; } public void setClientData(ClientRunningData clientData) { this.clientData = clientData; } public void setDelayTime(int delayTime) { this.delayTime = delayTime; } public void setZkClient(ZkClientx zkClient) { this.zkClient = zkClient; } }
client/src/main/java/com/alibaba/otter/canal/client/impl/running/ClientRunningMonitor.java
package com.alibaba.otter.canal.client.impl.running; import java.net.InetSocketAddress; import java.text.MessageFormat; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.I0Itec.zkclient.IZkDataListener; import org.I0Itec.zkclient.exception.ZkException; import org.I0Itec.zkclient.exception.ZkInterruptedException; import org.I0Itec.zkclient.exception.ZkNoNodeException; import org.I0Itec.zkclient.exception.ZkNodeExistsException; import org.apache.zookeeper.CreateMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import com.alibaba.otter.canal.common.AbstractCanalLifeCycle; import com.alibaba.otter.canal.common.utils.BooleanMutex; import com.alibaba.otter.canal.common.utils.JsonUtils; import com.alibaba.otter.canal.common.zookeeper.ZkClientx; import com.alibaba.otter.canal.common.zookeeper.ZookeeperPathUtils; import com.alibaba.otter.canal.protocol.exception.CanalClientException; /** * clinet running控制 * * @author jianghang 2012-11-22 下午03:43:01 * @version 1.0.0 */ public class ClientRunningMonitor extends AbstractCanalLifeCycle { private static final Logger logger = LoggerFactory.getLogger(ClientRunningMonitor.class); private ZkClientx zkClient; private String destination; private ClientRunningData clientData; private IZkDataListener dataListener; private BooleanMutex mutex = new BooleanMutex(false); private volatile boolean release = false; private volatile ClientRunningData activeData; private ScheduledExecutorService delayExector = Executors.newScheduledThreadPool(1); private ClientRunningListener listener; private int delayTime = 5; public ClientRunningMonitor(){ dataListener = new IZkDataListener() { public void handleDataChange(String dataPath, Object data) throws Exception { MDC.put("destination", destination); ClientRunningData runningData = JsonUtils.unmarshalFromByte((byte[]) data, ClientRunningData.class); if (!isMine(runningData.getAddress())) { mutex.set(false); } if (!runningData.isActive() && isMine(runningData.getAddress())) { // 说明出现了主动释放的操作,并且本机之前是active release = true; releaseRunning();// 彻底释放mainstem } activeData = (ClientRunningData) runningData; } public void handleDataDeleted(String dataPath) throws Exception { MDC.put("destination", destination); mutex.set(false); if (!release && activeData != null && isMine(activeData.getAddress())) { // 如果上一次active的状态就是本机,则即时触发一下active抢占 initRunning(); } else { // 否则就是等待delayTime,避免因网络瞬端或者zk异常,导致出现频繁的切换操作 delayExector.schedule(new Runnable() { public void run() { initRunning(); } }, delayTime, TimeUnit.SECONDS); } } }; } public void start() { super.start(); String path = ZookeeperPathUtils.getDestinationClientRunning(this.destination, clientData.getClientId()); zkClient.subscribeDataChanges(path, dataListener); initRunning(); } public void stop() { super.stop(); String path = ZookeeperPathUtils.getDestinationClientRunning(this.destination, clientData.getClientId()); zkClient.unsubscribeDataChanges(path, dataListener); releaseRunning(); // 尝试一下release } // 改动记录: // 1,在方法上加synchronized关键字,保证同步顺序执行; // 2,判断Zk上已经存在的activeData是否是本机,是的话把mutex重置为true,否则会导致死锁 // 3,增加异常处理,保证出现异常时,running节点能被删除,否则会导致死锁 public synchronized void initRunning() { if (!isStart()) { return; } String path = ZookeeperPathUtils.getDestinationClientRunning(this.destination, clientData.getClientId()); // 序列化 byte[] bytes = JsonUtils.marshalToByte(clientData); try { mutex.set(false); zkClient.create(path, bytes, CreateMode.EPHEMERAL); processActiveEnter();// 触发一下事件 activeData = clientData; mutex.set(true); } catch (ZkNodeExistsException e) { bytes = zkClient.readData(path, true); if (bytes == null) {// 如果不存在节点,立即尝试一次 initRunning(); } else { activeData = JsonUtils.unmarshalFromByte(bytes, ClientRunningData.class); // 如果发现已经存在,判断一下是否自己,避免活锁 if (activeData.getAddress().contains(":") && isMine(activeData.getAddress())) { mutex.set(true); } } } catch (ZkNoNodeException e) { zkClient.createPersistent(ZookeeperPathUtils.getClientIdNodePath(this.destination, clientData.getClientId()), true); // 尝试创建父节点 initRunning(); } catch (Throwable t) { logger.error(MessageFormat.format("There is an error when execute initRunning method, with destination [{0}].", destination), t); // 出现任何异常尝试release releaseRunning(); throw new CanalClientException("something goes wrong in initRunning method. ", t); } } /** * 阻塞等待自己成为active,如果自己成为active,立马返回 * * @throws InterruptedException */ public void waitForActive() throws InterruptedException { initRunning(); mutex.get(); } /** * 检查当前的状态 */ public boolean check() { String path = ZookeeperPathUtils.getDestinationClientRunning(this.destination, clientData.getClientId()); try { byte[] bytes = zkClient.readData(path); ClientRunningData eventData = JsonUtils.unmarshalFromByte(bytes, ClientRunningData.class); activeData = eventData;// 更新下为最新值 // 检查下nid是否为自己 boolean result = isMine(activeData.getAddress()); if (!result) { logger.warn("canal is running in [{}] , but not in [{}]", activeData.getAddress(), clientData.getAddress()); } return result; } catch (ZkNoNodeException e) { logger.warn("canal is not run any in node"); return false; } catch (ZkInterruptedException e) { logger.warn("canal check is interrupt"); Thread.interrupted();// 清除interrupt标记 return check(); } catch (ZkException e) { logger.warn("canal check is failed"); return false; } } public boolean releaseRunning() { if (check()) { String path = ZookeeperPathUtils.getDestinationClientRunning(this.destination, clientData.getClientId()); zkClient.delete(path); mutex.set(false); processActiveExit(); return true; } return false; } // ====================== helper method ====================== private boolean isMine(String address) { return address.equals(clientData.getAddress()); } private void processActiveEnter() { if (listener != null) { // 触发回调,建立与server的socket链接 InetSocketAddress connectAddress = listener.processActiveEnter(); String address = connectAddress.getAddress().getHostAddress() + ":" + connectAddress.getPort(); this.clientData.setAddress(address); String path = ZookeeperPathUtils.getDestinationClientRunning(this.destination, this.clientData.getClientId()); // 序列化 byte[] bytes = JsonUtils.marshalToByte(clientData); zkClient.writeData(path, bytes); } } private void processActiveExit() { if (listener != null) { listener.processActiveExit(); } } public void setListener(ClientRunningListener listener) { this.listener = listener; } // ===================== setter / getter ======================= public void setDestination(String destination) { this.destination = destination; } public void setClientData(ClientRunningData clientData) { this.clientData = clientData; } public void setDelayTime(int delayTime) { this.delayTime = delayTime; } public void setZkClient(ZkClientx zkClient) { this.zkClient = zkClient; } }
fixed issue #176 , handle running deleted
client/src/main/java/com/alibaba/otter/canal/client/impl/running/ClientRunningMonitor.java
fixed issue #176 , handle running deleted
<ide><path>lient/src/main/java/com/alibaba/otter/canal/client/impl/running/ClientRunningMonitor.java <ide> public void handleDataDeleted(String dataPath) throws Exception { <ide> MDC.put("destination", destination); <ide> mutex.set(false); <add> // 触发一下退出,可能是人为干预的释放操作或者网络闪断引起的session expired timeout <add> processActiveExit(); <ide> if (!release && activeData != null && isMine(activeData.getAddress())) { <ide> // 如果上一次active的状态就是本机,则即时触发一下active抢占 <ide> initRunning();
Java
apache-2.0
818ee868dd27cea2e6bb60e90590ab74cc5bf05a
0
blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.publish.tasks; import com.google.common.collect.ImmutableSet; import org.gradle.api.Buildable; import org.gradle.api.DefaultTask; import org.gradle.api.Task; import org.gradle.api.UncheckedIOException; import org.gradle.api.artifacts.PublishArtifact; import org.gradle.api.file.FileCollection; import org.gradle.api.file.RegularFileProperty; import org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectDependencyPublicationResolver; import org.gradle.api.internal.component.SoftwareComponentInternal; import org.gradle.api.internal.component.UsageContext; import org.gradle.api.internal.file.FileCollectionFactory; import org.gradle.api.internal.file.collections.MinimalFileSet; import org.gradle.api.internal.project.ProjectInternal; import org.gradle.api.internal.tasks.DefaultTaskDependency; import org.gradle.api.model.ObjectFactory; import org.gradle.api.provider.ListProperty; import org.gradle.api.provider.Property; import org.gradle.api.publish.Publication; import org.gradle.api.publish.internal.GradleModuleMetadataWriter; import org.gradle.api.publish.internal.PublicationInternal; import org.gradle.api.specs.Specs; import org.gradle.api.tasks.InputFiles; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.PathSensitive; import org.gradle.api.tasks.PathSensitivity; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.TaskDependency; import org.gradle.internal.Cast; import org.gradle.internal.hash.ChecksumService; import org.gradle.internal.scopeids.id.BuildInvocationScopeId; import javax.inject.Inject; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * Generates a Gradle metadata file to represent a published {@link org.gradle.api.component.SoftwareComponent} instance. * * @since 4.3 */ public class GenerateModuleMetadata extends DefaultTask { private final Property<Publication> publication; private final ListProperty<Publication> publications; private final RegularFileProperty outputFile; private final ChecksumService checksumService; public GenerateModuleMetadata() { ObjectFactory objectFactory = getProject().getObjects(); publication = objectFactory.property(Publication.class); publications = objectFactory.listProperty(Publication.class); outputFile = objectFactory.fileProperty(); // TODO - should be incremental getOutputs().upToDateWhen(Specs.<Task>satisfyNone()); mustHaveAttachedComponent(); // injected here in order to avoid exposing in public API checksumService = ((ProjectInternal)getProject()).getServices().get(ChecksumService.class); } private void mustHaveAttachedComponent() { setOnlyIf(element -> { PublicationInternal publication = (PublicationInternal) GenerateModuleMetadata.this.publication.get(); if (publication.getComponent() == null) { getLogger().warn(publication.getDisplayName() + " isn't attached to a component. Gradle metadata only supports publications with software components (e.g. from component.java)"); return false; } return true; }); } // TODO - this should be an input /** * Returns the publication to generate the metadata file for. */ @Internal public Property<Publication> getPublication() { return publication; } // TODO - this should be an input /** * Returns the publications of the current project, used in generation to connect the modules of a component together. * * @since 4.4 */ @Internal public ListProperty<Publication> getPublications() { return publications; } @InputFiles @PathSensitive(PathSensitivity.NAME_ONLY) FileCollection getArtifacts() { return getFileCollectionFactory().create(new VariantFiles()); } /** * Returns the {@link FileCollectionFactory} to use for generation. * * @since 4.4 */ @Inject protected FileCollectionFactory getFileCollectionFactory() { throw new UnsupportedOperationException(); } /** * Returns the {@link BuildInvocationScopeId} to use for generation. * * @since 4.4 */ @Inject protected BuildInvocationScopeId getBuildInvocationScopeId() { throw new UnsupportedOperationException(); } /** * Returns the {@link ProjectDependencyPublicationResolver} to use for generation. * * @since 4.4 */ @Inject protected ProjectDependencyPublicationResolver getProjectDependencyPublicationResolver() { throw new UnsupportedOperationException(); } /** * Returns the output file location. */ @OutputFile public RegularFileProperty getOutputFile() { return outputFile; } @TaskAction void run() { File file = outputFile.get().getAsFile(); PublicationInternal publication = (PublicationInternal) this.publication.get(); List<PublicationInternal> publications = Cast.uncheckedCast(this.publications.get()); try { Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf8")); try { new GradleModuleMetadataWriter(getBuildInvocationScopeId(), getProjectDependencyPublicationResolver(), checksumService).generateTo(publication, publications, writer); } finally { writer.close(); } } catch (IOException e) { throw new UncheckedIOException("Could not generate metadata file " + outputFile.get(), e); } } private class VariantFiles implements MinimalFileSet, Buildable { @Override public TaskDependency getBuildDependencies() { PublicationInternal publication = (PublicationInternal) GenerateModuleMetadata.this.publication.get(); SoftwareComponentInternal component = publication.getComponent(); DefaultTaskDependency dependency = new DefaultTaskDependency(); if (component == null) { return dependency; } for (UsageContext usageContext : component.getUsages()) { for (PublishArtifact publishArtifact : usageContext.getArtifacts()) { dependency.add(publishArtifact); } } return dependency; } @Override public Set<File> getFiles() { PublicationInternal publication = (PublicationInternal) GenerateModuleMetadata.this.publication.get(); SoftwareComponentInternal component = publication.getComponent(); if (component == null) { return ImmutableSet.of(); } Set<File> files = new LinkedHashSet<File>(); for (UsageContext usageContext : component.getUsages()) { for (PublishArtifact publishArtifact : usageContext.getArtifacts()) { files.add(publishArtifact.getFile()); } } return files; } @Override public String getDisplayName() { return "files of " + GenerateModuleMetadata.this.getPath(); } } }
subprojects/publish/src/main/java/org/gradle/api/publish/tasks/GenerateModuleMetadata.java
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.publish.tasks; import com.google.common.collect.ImmutableSet; import org.gradle.api.Buildable; import org.gradle.api.DefaultTask; import org.gradle.api.Task; import org.gradle.api.UncheckedIOException; import org.gradle.api.artifacts.PublishArtifact; import org.gradle.api.file.FileCollection; import org.gradle.api.file.RegularFileProperty; import org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectDependencyPublicationResolver; import org.gradle.api.internal.component.SoftwareComponentInternal; import org.gradle.api.internal.component.UsageContext; import org.gradle.api.internal.file.FileCollectionFactory; import org.gradle.api.internal.file.collections.MinimalFileSet; import org.gradle.api.internal.project.ProjectInternal; import org.gradle.api.internal.tasks.DefaultTaskDependency; import org.gradle.api.model.ObjectFactory; import org.gradle.api.provider.ListProperty; import org.gradle.api.provider.Property; import org.gradle.api.publish.Publication; import org.gradle.api.publish.internal.GradleModuleMetadataWriter; import org.gradle.api.publish.internal.PublicationInternal; import org.gradle.api.specs.Specs; import org.gradle.api.tasks.InputFiles; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.PathSensitive; import org.gradle.api.tasks.PathSensitivity; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.TaskDependency; import org.gradle.internal.Cast; import org.gradle.internal.hash.ChecksumService; import org.gradle.internal.scopeids.id.BuildInvocationScopeId; import javax.inject.Inject; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.function.Supplier; /** * Generates a Gradle metadata file to represent a published {@link org.gradle.api.component.SoftwareComponent} instance. * * @since 4.3 */ public class GenerateModuleMetadata extends DefaultTask { private final Property<Publication> publication; private final ListProperty<Publication> publications; private final RegularFileProperty outputFile; private final ChecksumService checksumService; private Supplier<Boolean> enabledIf; public GenerateModuleMetadata() { ObjectFactory objectFactory = getProject().getObjects(); publication = objectFactory.property(Publication.class); publications = objectFactory.listProperty(Publication.class); outputFile = objectFactory.fileProperty(); // TODO - should be incremental getOutputs().upToDateWhen(Specs.<Task>satisfyNone()); mustHaveAttachedComponent(); // injected here in order to avoid exposing in public API checksumService = ((ProjectInternal)getProject()).getServices().get(ChecksumService.class); } private void mustHaveAttachedComponent() { setOnlyIf(element -> { PublicationInternal publication = (PublicationInternal) GenerateModuleMetadata.this.publication.get(); if (publication.getComponent() == null) { getLogger().warn(publication.getDisplayName() + " isn't attached to a component. Gradle metadata only supports publications with software components (e.g. from component.java)"); return false; } return true; }); } // TODO - this should be an input /** * Returns the publication to generate the metadata file for. */ @Internal public Property<Publication> getPublication() { return publication; } // TODO - this should be an input /** * Returns the publications of the current project, used in generation to connect the modules of a component together. * * @since 4.4 */ @Internal public ListProperty<Publication> getPublications() { return publications; } @InputFiles @PathSensitive(PathSensitivity.NAME_ONLY) FileCollection getArtifacts() { return getFileCollectionFactory().create(new VariantFiles()); } /** * Returns the {@link FileCollectionFactory} to use for generation. * * @since 4.4 */ @Inject protected FileCollectionFactory getFileCollectionFactory() { throw new UnsupportedOperationException(); } /** * Returns the {@link BuildInvocationScopeId} to use for generation. * * @since 4.4 */ @Inject protected BuildInvocationScopeId getBuildInvocationScopeId() { throw new UnsupportedOperationException(); } /** * Returns the {@link ProjectDependencyPublicationResolver} to use for generation. * * @since 4.4 */ @Inject protected ProjectDependencyPublicationResolver getProjectDependencyPublicationResolver() { throw new UnsupportedOperationException(); } /** * Returns the output file location. */ @OutputFile public RegularFileProperty getOutputFile() { return outputFile; } @TaskAction void run() { File file = outputFile.get().getAsFile(); PublicationInternal publication = (PublicationInternal) this.publication.get(); List<PublicationInternal> publications = Cast.uncheckedCast(this.publications.get()); try { Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf8")); try { new GradleModuleMetadataWriter(getBuildInvocationScopeId(), getProjectDependencyPublicationResolver(), checksumService).generateTo(publication, publications, writer); } finally { writer.close(); } } catch (IOException e) { throw new UncheckedIOException("Could not generate metadata file " + outputFile.get(), e); } } private class VariantFiles implements MinimalFileSet, Buildable { @Override public TaskDependency getBuildDependencies() { PublicationInternal publication = (PublicationInternal) GenerateModuleMetadata.this.publication.get(); SoftwareComponentInternal component = publication.getComponent(); DefaultTaskDependency dependency = new DefaultTaskDependency(); if (component == null) { return dependency; } for (UsageContext usageContext : component.getUsages()) { for (PublishArtifact publishArtifact : usageContext.getArtifacts()) { dependency.add(publishArtifact); } } return dependency; } @Override public Set<File> getFiles() { PublicationInternal publication = (PublicationInternal) GenerateModuleMetadata.this.publication.get(); SoftwareComponentInternal component = publication.getComponent(); if (component == null) { return ImmutableSet.of(); } Set<File> files = new LinkedHashSet<File>(); for (UsageContext usageContext : component.getUsages()) { for (PublishArtifact publishArtifact : usageContext.getArtifacts()) { files.add(publishArtifact.getFile()); } } return files; } @Override public String getDisplayName() { return "files of " + GenerateModuleMetadata.this.getPath(); } } }
Remove unused field
subprojects/publish/src/main/java/org/gradle/api/publish/tasks/GenerateModuleMetadata.java
Remove unused field
<ide><path>ubprojects/publish/src/main/java/org/gradle/api/publish/tasks/GenerateModuleMetadata.java <ide> import java.util.LinkedHashSet; <ide> import java.util.List; <ide> import java.util.Set; <del>import java.util.function.Supplier; <ide> <ide> /** <ide> * Generates a Gradle metadata file to represent a published {@link org.gradle.api.component.SoftwareComponent} instance. <ide> private final ListProperty<Publication> publications; <ide> private final RegularFileProperty outputFile; <ide> private final ChecksumService checksumService; <del> private Supplier<Boolean> enabledIf; <ide> <ide> public GenerateModuleMetadata() { <ide> ObjectFactory objectFactory = getProject().getObjects();
JavaScript
agpl-3.0
5bf4cc5c23494fc28a3c95df0342e98e0f0c31a8
0
denkbar/step,denkbar/step,denkbar/step,denkbar/step,denkbar/step
/******************************************************************************* * (C) Copyright 2016 Jerome Comte and Dorian Cransac * * This file is part of STEP * * STEP is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * STEP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with STEP. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ angular.module('adminControllers', [ 'dataTable', 'step' ]) .controller('AdminCtrl', ['$scope', 'stateStorage', function($scope) { $scope.autorefresh = true; }]) .controller('UserListCtrl', function($scope, $interval, $http, helpers, $uibModal, Dialogs) { $scope.datatable = {} $scope.loadTable = function loadTable() { $http.get("rest/admin/users").then( function(response) { var data = response.data; var dataSet = []; for (i = 0; i < data.length; i++) { dataSet[i] = [ data[i].username, data[i].role]; } $scope.tabledef.data = dataSet; }); }; $scope.tabledef = {}; $scope.tabledef.columns = [ { "title" : "Username"}, { "title" : "Role" }, {"title":"Actions", "width":"120px", "render":function ( data, type, row ) { var html = '<div class="input-group">' + '<div class="btn-group">' + '<button type="button" class="btn btn-default" aria-label="Left Align" onclick="angular.element(\'#UserListCtrl\').scope().editUser(\''+row[0]+'\')">' + '<span class="glyphicon glyphicon glyphicon glyphicon-pencil" aria-hidden="true"></span>' + '<button type="button" class="btn btn-default" aria-label="Left Align" onclick="angular.element(\'#UserListCtrl\').scope().askAndRemoveUser(\''+row[0]+'\')">' + '<span class="glyphicon glyphicon glyphicon glyphicon-trash" aria-hidden="true"></span>' + '</button> '+ '</div></div>'; return html; }}]; $scope.loadTable(); $scope.forAllSelected = function(fctName) { var rows = $scope.datatable.getSelection().selectedItems; var itemCount = rows.length; if(itemCount >= 1) { var msg = itemCount == 1? 'Are you sure you want to perform this operation for this item?':'Are you sure you want to perform this operation for these ' + itemCount + ' items?'; Dialogs.showWarning(msg).then(function() { for(i=0;i<rows.length;i++) { $scope[fctName](rows[i][0]); } }) } else { Dialogs.showErrorMsg("You haven't selected any item"); } }; $scope.resetPwd = function(id) { $http.post("rest/admin/user/"+id+"/resetpwd").then(function() { $scope.loadTable(); }); } $scope.askAndRemoveUser = function(username) { Dialogs.showDeleteWarning().then(function() { $scope.removeUser(username) }) } $scope.removeUser = function(username) { $http.delete("rest/admin/user/"+username).then(function() { $scope.loadTable(); }); } $scope.addUser = function() { $scope.showEditUserPopup({}); } $scope.editUser = function(username) { $http.get("rest/admin/user/"+username).then(function(response) { var user = response.data; $scope.showEditUserPopup(user); }); } $scope.showEditUserPopup = function(user) { var modalInstance = $uibModal.open({ animation: $scope.animationsEnabled, templateUrl: 'editUserModalContent.html', controller: 'editUserModalCtrl', resolve: { user: function () { return user; } } }); modalInstance.result.then(function() {$scope.loadTable()}, function () {}); } }) .run(function(ViewRegistry) { ViewRegistry.registerDashlet('admin/controller','Maintenance','partials/maintenanceConfiguration.html'); }) .controller('ControllerSettingsCtrl', function($scope, $http, ViewRegistry) { $scope.configurationItems = ViewRegistry.getDashlets("admin/controller"); $scope.currentConfigurationItem = $scope.configurationItems[0]; $scope.setCurrentConfigurationItem = function(item) { $scope.currentConfigurationItem = item; } }) .controller('MaintenanceSettingsCtrl', function($scope, $http, ViewRegistry, MaintenanceService) { $scope.maintenanceMessage; $scope.toggle = {}; $scope.toggle.switch = false; $http.get("rest/admin/maintenance/message").then(function(res) { $scope.maintenanceMessage = res.data; }); $http.get("rest/admin/maintenance/message/toggle").then(function(res) { $scope.toggle.switch = (res.data === 'true'); }); $scope.saveMaintenanceMessage = function() { $http.post("rest/admin/maintenance/message", $scope.maintenanceMessage).then(function() { MaintenanceService.reloadMaintenanceMessage(); }); } $scope.upateToggle = function() { $http.post("rest/admin/maintenance/message/toggle", $scope.toggle.switch).then(function() { MaintenanceService.reloadMaintenanceMessage(); }); } $scope.switchToggle = function() { $scope.toggle.switch = !$scope.toggle.switch; $scope.upateToggle(); } }) .controller('editUserModalCtrl', function ($scope, $uibModalInstance, $http, $location, AuthService, user) { $scope.roles = AuthService.getConf().roles; $scope.user = user; if(!user.role) { user.role = $scope.roles[0]; } $scope.save = function() { $http.post("rest/admin/user", user).then(function() { $uibModalInstance.close(); }); } $scope.cancel = function() { $uibModalInstance.close(); } }) .controller('MyAccountCtrl', function($scope, $rootScope, $interval, $http, helpers, $uibModal) { $scope.$state = 'myaccount'; $scope.changePwd=function() { $uibModal.open({animation: false,templateUrl: 'partials/changePasswordForm.html', controller: 'ChangePasswordModalCtrl', resolve: {}}); } $scope.user = {}; $http.get("rest/admin/myaccount").then(function(response) { var user = response.data; $scope.user=user; $scope.preferences = []; if($scope.user.preferences) { _.mapObject($scope.user.preferences.preferences,function(val,key) { $scope.preferences.push({key:key,value:val}); }); } }); $scope.addPreference = function() { $scope.preferences.push({key:"",value:""}); } $scope.savePreferences = function() { var preferences = {preferences:{}}; _.each($scope.preferences, function(entry) { preferences.preferences[entry.key]=entry.value; }); $http.post("rest/admin/myaccount/preferences",preferences).then(function() { },function() { $scope.error = "Unable to save preferences. Please contact your administrator."; }); } }) .controller('ChangePasswordModalCtrl', function ($scope, $rootScope, $uibModalInstance, $http, $location) { $scope.model = {newPwd:""}; $scope.repeatPwd = "" $scope.save = function () { if($scope.repeatPwd!=$scope.model.newPwd) { $scope.error = "New password doesn't match" } else { $http.post("rest/admin/myaccount/changepwd",$scope.model).then(function() { $uibModalInstance.close(); },function() { $scope.error = "Unable to change password. Please contact your administrator."; }); } }; $scope.cancel = function () { $uibModalInstance.close(); }; });
step-controller/step-controller-server-webapp/src/main/resources/webapp/js/controllers/admin.js
/******************************************************************************* * (C) Copyright 2016 Jerome Comte and Dorian Cransac * * This file is part of STEP * * STEP is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * STEP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with STEP. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ angular.module('adminControllers', [ 'dataTable', 'step' ]) .controller('AdminCtrl', ['$scope', 'stateStorage', function($scope) { $scope.autorefresh = true; }]) .controller('UserListCtrl', function($scope, $interval, $http, helpers, $uibModal, Dialogs) { $scope.datatable = {} $scope.loadTable = function loadTable() { $http.get("rest/admin/users").then( function(response) { var data = response.data; var dataSet = []; for (i = 0; i < data.length; i++) { dataSet[i] = [ data[i].username, data[i].role]; } $scope.tabledef.data = dataSet; }); }; $scope.tabledef = {}; $scope.tabledef.columns = [ { "title" : "Username"}, { "title" : "Role" }, {"title":"Actions", "width":"120px", "render":function ( data, type, row ) { var html = '<div class="input-group">' + '<div class="btn-group">' + '<button type="button" class="btn btn-default" aria-label="Left Align" onclick="angular.element(\'#UserListCtrl\').scope().editUser(\''+row[0]+'\')">' + '<span class="glyphicon glyphicon glyphicon glyphicon-pencil" aria-hidden="true"></span>' + '<button type="button" class="btn btn-default" aria-label="Left Align" onclick="angular.element(\'#UserListCtrl\').scope().askAndRemoveUser(\''+row[0]+'\')">' + '<span class="glyphicon glyphicon glyphicon glyphicon-trash" aria-hidden="true"></span>' + '</button> '+ '</div></div>'; return html; }}]; $scope.loadTable(); $scope.forAllSelected = function(fctName) { var rows = $scope.datatable.getSelection().selectedItems; var itemCount = rows.length; if(itemCount >= 1) { var msg = itemCount == 1? 'Are you sure you want to perform this operation for this item?':'Are you sure you want to perform this operation for these ' + itemCount + ' items?'; Dialogs.showWarning(msg).then(function() { for(i=0;i<rows.length;i++) { $scope[fctName](rows[i][0]); } }) } else { Dialogs.showErrorMsg("You haven't selected any item"); } }; $scope.resetPwd = function(id) { $http.post("rest/admin/user/"+id+"/resetpwd").then(function() { $scope.loadTable(); }); } $scope.askAndRemoveUser = function(username) { Dialogs.showDeleteWarning().then(function() { $scope.removeUser(username) }) } $scope.removeUser = function(username) { $http.delete("rest/admin/user/"+username).then(function() { $scope.loadTable(); }); } $scope.addUser = function() { $scope.showEditUserPopup({}); } $scope.editUser = function(username) { $http.get("rest/admin/user/"+username).then(function(response) { var user = response.data; $scope.showEditUserPopup(user); }); } $scope.showEditUserPopup = function(user) { var modalInstance = $uibModal.open({ animation: $scope.animationsEnabled, templateUrl: 'editUserModalContent.html', controller: 'editUserModalCtrl', resolve: { user: function () { return user; } } }); modalInstance.result.then(function() {$scope.loadTable()}, function () {}); } }) .run(function(ViewRegistry) { ViewRegistry.registerDashlet('admin/controller','Maintenance','partials/maintenanceConfiguration.html'); }) .controller('ControllerSettingsCtrl', function($scope, $http, ViewRegistry) { $scope.configurationItems = ViewRegistry.getDashlets("admin/controller"); $scope.currentConfigurationItem; $scope.setCurrentConfigurationItem = function(item) { $scope.currentConfigurationItem = item; } }) .controller('MaintenanceSettingsCtrl', function($scope, $http, ViewRegistry, MaintenanceService) { $scope.maintenanceMessage; $scope.toggle = {}; $scope.toggle.switch = false; $http.get("rest/admin/maintenance/message").then(function(res) { $scope.maintenanceMessage = res.data; }); $http.get("rest/admin/maintenance/message/toggle").then(function(res) { $scope.toggle.switch = (res.data === 'true'); }); $scope.saveMaintenanceMessage = function() { $http.post("rest/admin/maintenance/message", $scope.maintenanceMessage).then(function() { MaintenanceService.reloadMaintenanceMessage(); }); } $scope.upateToggle = function() { $http.post("rest/admin/maintenance/message/toggle", $scope.toggle.switch).then(function() { MaintenanceService.reloadMaintenanceMessage(); }); } $scope.switchToggle = function() { $scope.toggle.switch = !$scope.toggle.switch; $scope.upateToggle(); } }) .controller('editUserModalCtrl', function ($scope, $uibModalInstance, $http, $location, AuthService, user) { $scope.roles = AuthService.getConf().roles; $scope.user = user; if(!user.role) { user.role = $scope.roles[0]; } $scope.save = function() { $http.post("rest/admin/user", user).then(function() { $uibModalInstance.close(); }); } $scope.cancel = function() { $uibModalInstance.close(); } }) .controller('MyAccountCtrl', function($scope, $rootScope, $interval, $http, helpers, $uibModal) { $scope.$state = 'myaccount'; $scope.changePwd=function() { $uibModal.open({animation: false,templateUrl: 'partials/changePasswordForm.html', controller: 'ChangePasswordModalCtrl', resolve: {}}); } $scope.user = {}; $http.get("rest/admin/myaccount").then(function(response) { var user = response.data; $scope.user=user; $scope.preferences = []; if($scope.user.preferences) { _.mapObject($scope.user.preferences.preferences,function(val,key) { $scope.preferences.push({key:key,value:val}); }); } }); $scope.addPreference = function() { $scope.preferences.push({key:"",value:""}); } $scope.savePreferences = function() { var preferences = {preferences:{}}; _.each($scope.preferences, function(entry) { preferences.preferences[entry.key]=entry.value; }); $http.post("rest/admin/myaccount/preferences",preferences).then(function() { },function() { $scope.error = "Unable to save preferences. Please contact your administrator."; }); } }) .controller('ChangePasswordModalCtrl', function ($scope, $rootScope, $uibModalInstance, $http, $location) { $scope.model = {newPwd:""}; $scope.repeatPwd = "" $scope.save = function () { if($scope.repeatPwd!=$scope.model.newPwd) { $scope.error = "New password doesn't match" } else { $http.post("rest/admin/myaccount/changepwd",$scope.model).then(function() { $uibModalInstance.close(); },function() { $scope.error = "Unable to change password. Please contact your administrator."; }); } }; $scope.cancel = function () { $uibModalInstance.close(); }; });
Adding a default screen to the Admin->Settings tab
step-controller/step-controller-server-webapp/src/main/resources/webapp/js/controllers/admin.js
Adding a default screen to the Admin->Settings tab
<ide><path>tep-controller/step-controller-server-webapp/src/main/resources/webapp/js/controllers/admin.js <ide> <ide> .controller('ControllerSettingsCtrl', function($scope, $http, ViewRegistry) { <ide> $scope.configurationItems = ViewRegistry.getDashlets("admin/controller"); <del> <del> $scope.currentConfigurationItem; <add> <add> $scope.currentConfigurationItem = $scope.configurationItems[0]; <ide> <ide> $scope.setCurrentConfigurationItem = function(item) { <ide> $scope.currentConfigurationItem = item;
JavaScript
mit
e5efa3bfda15a50cbaee7db8eb9d686e18468b56
0
grxanon/grxanon.github.io,grxanon/grxanon.github.io,TheGiddyLimit/astranauta.github.io,grxanon/grxanon.github.io,TheGiddyLimit/astranauta.github.io
var tabledefault=""; var classtabledefault =""; let classlist; window.onload = function load() { let jsonURL = "data/classes.json"; let request = new XMLHttpRequest(); request.open('GET', jsonURL, true); request.onload = function() { let data = JSON.parse(this.response); classlist = data.class; tabledefault = $("#stats").html(); statsprofdefault = $("#statsprof").html(); classtabledefault = $("#classtable").html(); for (let i = 0; i < classlist.length; i++) { var curclass = classlist[i]; $("ul.classes").append("<li><a id='"+i+"' href='#"+encodeURI(curclass.name).toLowerCase()+"' title='"+curclass.name+"'><span class='name col-xs-9'>"+curclass.name+"</span><span class='source col-xs-3' title='"+parse_sourceToFull(curclass.source)+"'>"+curclass.source+"</span></a></li>"); } const list = search({ valueNames: ['name', 'source'], listClass: "classes" }); if (window.location.hash.length) { window.onhashchange(); } else $("#listcontainer a").get(0).click(); }; request.send(); } function loadhash (id) { $("#stats").html(tabledefault); $("#statsprof").html(statsprofdefault); $("#classtable").html(classtabledefault); var curclass = classlist[id]; $("th#name").html(curclass.name); $("td#hp div#hitdice span").html("1d"+curclass.hd); $("td#hp div#hp1stlevel span").html(curclass.hd+" + your Constitution modifier"); $("td#hp div#hphigherlevels span").html("1d"+curclass.hd+" (or "+(curclass.hd/2+1)+") + your Constitution modifier per "+curclass.name+" level after 1st"); $("td#prof div#saves span").html(curclass.proficiency); $("tr:has(.slotlabel)").hide(); $("#classtable tr").not(":has(th)").append("<td class='featurebuffer'></td>"); var subclasses = []; for (let i = curclass.autolevel.length-1; i >= 0; i--) { var curlevel = curclass.autolevel[i]; // spell slots and table data if (!curlevel.feature) { if (curlevel.slots) { $("tr:has(.slotlabel)").show(); if (curlevel.slots.__text) curlevel.slots = curlevel.slots.__text; var curslots = curlevel.slots.split(","); if (curslots[0] !== "0" && $("th.slotbuffer").attr("colspan") < 4) { $("#classtable td.border").attr("colspan", parseInt($("#classtable td.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("th.slotlabel").attr("colspan", curslots.length-1); if (curslots.length > 1) $(".featurebuffer").hide(); for (var a = 0; a < curslots.length; a++) { if (curslots[a] === "0") continue; $(".spellslots"+a).show(); $("tr#level"+curlevel._level+" td.spellslots"+a).html(curslots[a]); } } if (curlevel.spellsknown) { if (!$(".spellsknown").length) { $("th.spellslots0").after("<th class='spellsknown newfeature'>Spells Known</th>"); $("td.spellslots0").after("<td class='spellsknown newfeature'></td>"); $("#classtable th.border").attr("colspan", parseInt($("#classtable th.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("tr#level"+curlevel._level+" td.spellsknown").html(curlevel.spellsknown); } if (curlevel.invocationsknown) { if (!$(".invocationsknown").length) { $("th.spellslots5").after("<th class='spellslots newfeature'>Spell Slots</th> <th class='slotlevel newfeature'>Slot Level</th> <th class='invocationsknown newfeature'>Invocations Known</th>"); $("td.spellslots5").after("<td class='spellslots newfeature'></td> <td class='slotlevel newfeature'></td> <td class='invocationsknown newfeature'>Invocations Known</td>"); $("#classtable th.border").attr("colspan", parseInt($("#classtable th.border").attr("colspan"))+3); } $(".spellslots5").hide(); $("tr#level"+curlevel._level+" td.spellslots").html(curlevel.spellslots); $("tr#level"+curlevel._level+" td.slotlevel").html(curlevel.slotlevel); $("tr#level"+curlevel._level+" td.invocationsknown").html(curlevel.invocationsknown); $("tr:has(.slotlabel)").hide(); } if (curlevel.rages) { if (!$(".rages").length) { $("th.spellslots0").before("<th class='rages newfeature'>Rages</th> <th class='ragedamage newfeature'>Rage Damage</th>"); $("td.spellslots0").before("<td class='rages newfeature'></td> <td class='ragedamage newfeature'></td>"); $("#classtable th.border").attr("colspan", parseInt($("#classtable th.border").attr("colspan"))+2); } $("tr#level"+curlevel._level+" td.rages").html(curlevel.rages); $("tr#level"+curlevel._level+" td.ragedamage").html(curlevel.ragedamage); } if (curlevel.martialarts) { if (!$(".kipoints").length) { $("th.pb").after("<th class='martialarts newfeature'>Martial Arts</th> <th class='kipoints newfeature'>Ki Points</th> <th class='unarmoredmovement newfeature'>Unarmored Movement</th>"); $("td.pb").after("<td class='martialarts newfeature'></td> <td class='kipoints newfeature'></td> <td class='unarmoredmovement newfeature'></td>"); $("#classtable td.border").attr("colspan", parseInt($("#classtable td.border").attr("colspan"))+3); $("th.slotbuffer").attr("colspan", $("th.slotbuffer").attr("colspan")+3); } $("tr#level"+curlevel._level+" td.martialarts").html(curlevel.martialarts); $("tr#level"+curlevel._level+" td.kipoints").html(curlevel.kipoints); $("tr#level"+curlevel._level+" td.unarmoredmovement").html(curlevel.unarmoredmovement); } if (curlevel.sneakattack) { if (!$(".sneakattack").length) { $("th.pb").after("<th class='sneakattack newfeature'>Sneak Attack</th>"); $("td.pb").after("<td class='sneakattack newfeature'></td>"); $("#classtable td.border").attr("colspan", parseInt($("#classtable td.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("tr#level"+curlevel._level+" td.sneakattack").html(curlevel.sneakattack); } if (curlevel.sorcerypoints) { if (!$(".sorcerypoints").length) { $("th.pb").after("<th class='sorcerypoints newfeature'>Sorcery Points</th>"); $("td.pb").after("<td class='sorcerypoints newfeature'></td>"); $("#classtable td.border").attr("colspan", parseInt($("#classtable td.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("tr#level"+curlevel._level+" td.sorcerypoints").html(curlevel.sorcerypoints); } if (curlevel.psilimit) { if (!$(".psilimit").length) { $("th.spellslots0").after("<th class='psilimit newfeature'>Psi Limit</th>"); $("td.spellslots0").after("<td class='psilimit newfeature'></td>"); $("#classtable th.border").attr("colspan", parseInt($("#classtable th.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("tr#level"+curlevel._level+" td.psilimit").html(curlevel.psilimit); } if (curlevel.psipoints) { if (!$(".psipoints").length) { $("th.spellslots0").after("<th class='psipoints newfeature'>Psi Points</th>"); $("td.spellslots0").after("<td class='psipoints newfeature'></td>"); $("#classtable th.border").attr("colspan", parseInt($("#classtable th.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("tr#level"+curlevel._level+" td.psipoints").html(curlevel.psipoints); } if (curlevel.disciplinesknown) { if (!$(".disciplinesknown").length) { $("th.spellslots0").after("<th class='disciplinesknown newfeature'>Disciplines Known</th>"); $("td.spellslots0").after("<td class='disciplinesknown newfeature'></td>"); $("#classtable th.border").attr("colspan", parseInt($("#classtable th.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("tr#level"+curlevel._level+" td.disciplinesknown").html(curlevel.disciplinesknown); } if (curlevel.talentsknown) { if (!$(".talentsknown").length) { $("th.spellslots0").after("<th class='talentsknown newfeature'>Talents Known</th>"); $("td.spellslots0").after("<td class='talentsknown newfeature'></td>"); $("#classtable th.border").attr("colspan", parseInt($("#classtable th.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("tr#level"+curlevel._level+" td.talentsknown").html(curlevel.talentsknown); } // other features } else for (let a = curlevel.feature.length-1; a >= 0; a--) { let curfeature = curlevel.feature[a]; let link = curlevel._level + "_" + a; if (curfeature._optional === "YES") { subclasses.push(curfeature); } let styleClass = ""; let isInlineHeader = curfeature.suboption === "2"; let removeSubclassNamePrefix = curfeature.subclass !== undefined && curfeature.suboption === undefined; let hasSubclassPrefix = curfeature.subclass !== undefined && curfeature.suboption === "1"; if (curfeature.subclass === undefined && curfeature.suboption === undefined) styleClass = "feature"; else if (curfeature.subclass === undefined && curfeature.suboption !== undefined && curfeature._optional === "YES") styleClass = "optionalsubfeature sub" + curfeature.suboption; else if (curfeature.subclass === undefined && curfeature.suboption !== undefined) styleClass = "subfeature sub" + curfeature.suboption; else if (curfeature.subclass !== undefined && curfeature.suboption === undefined) styleClass = "subclassfeature"; else if (curfeature.subclass !== undefined && curfeature.suboption !== undefined) styleClass = "subclasssubfeature sub" + curfeature.suboption; if (curfeature.name === "Starting Proficiencies") { $("td#prof div#armor span").html(curfeature.text[1].split(":")[1]); $("td#prof div#weapons span").html(curfeature.text[2].split(":")[1]); $("td#prof div#tools span").html(curfeature.text[3].split(":")[1]); $("td#prof div#skills span").html(curfeature.text[4].split(":")[1]); continue; } if (curfeature.name === "Starting Equipment") { $("#equipment div").html("<p>"+curfeature.text.join("</p><p>")); continue; } // write out list to class table var multifeature = ""; if (curlevel.feature.length !== 1 && a !== 0) multifeature = ", "; let featureSpan = document.createElement('span'); featureSpan.setAttribute('data-link', link); featureSpan.onclick = function() {scrollToFeature(featureSpan.getAttribute('data-link'))}; featureSpan.innerHTML = curfeature.name; if (curfeature._optional !== "YES" && curfeature.suboption === undefined) $("tr#level"+curlevel._level+" td.features").prepend(featureSpan).prepend(multifeature); // display features in bottom section var dataua = (curfeature.subclass !== undefined && curfeature.subclass.indexOf(" (UA)") !== -1) ? "true" : "false"; let subclassPrefix = hasSubclassPrefix ? "<span class='subclass-prefix'>" + curfeature.subclass.split(": ")[1] +": </span>" : ""; let dataSubclass = curfeature.subclass === undefined ? undefined : curfeature.subclass.toLowerCase(); if (isInlineHeader) { let namePart = curfeature.name === undefined ? null : "<span id='feature" + link + "' class='inline-header'>" + subclassPrefix + curfeature.name + ".</span> "; $("#features").after("<tr><td colspan='6' class='_class_feature " + styleClass + "' data-subclass='" + dataSubclass + "' data-ua='" + dataua + "'>" + utils_combineText(curfeature.text, "p", namePart) + "</td></tr>"); } else { let namePart = curfeature.name === undefined ? "" : "<strong id='feature" + link + "'>" + subclassPrefix + (removeSubclassNamePrefix ? curfeature.name.split(": ")[1] : curfeature.name) + "</strong>"; let prerequisitePart = curfeature.prerequisite === undefined ? "" : "<p class='prerequisite'>Prerequisite: " + curfeature.prerequisite + "</p>"; $("#features").after("<tr><td colspan='6' class='_class_feature " + styleClass + "' data-subclass='" + dataSubclass + "' data-ua='" + dataua + "'>" + namePart + prerequisitePart + utils_combineText(curfeature.text, "p") + "</td></tr>"); } } } $("td.features, td.slots, td.newfeature").each(function() { if ($(this).html() === "") $(this).html("\u2014") }); $("div#subclasses span").remove(); for (let i = 0; i < subclasses.length; i++) { if (subclasses[i].issubclass === "YES") $("div#subclasses").prepend("<span data-subclass='"+(subclasses[i].name.toLowerCase())+"'><em style='display: none;'>"+subclasses[i].name.split(": ")[0]+": </em><span>"+subclasses[i].name.split(": ")[1]+"</span></span>"); } $("#subclasses > span").sort(asc_sort).appendTo("#subclasses"); $("#subclasses > span").click(function() { const name = $(this).children("span").text() if ($(this).hasClass("active")) window.location.hash = window.location.hash.replace(/\,.*/, "").toLowerCase() else window.location.hash = window.location.hash.replace(/\,.*|$/, "," + encodeURIComponent(name).replace("'", "%27")).toLowerCase() }); return; } function scrollToFeature(ele) { let goTo = document.getElementById("feature"+ele); goTo.scrollIntoView(); } function loadsub(sub) { let subClassSpanList = document.getElementById("subclasses").getElementsByTagName("span"); let $el; for (let i = 0; i < subClassSpanList.length; ++i) { if (subClassSpanList[i].getAttribute('data-subclass') !== undefined && subClassSpanList[i].getAttribute('data-subclass') !== null && subClassSpanList[i].getAttribute('data-subclass').includes(decodeURIComponent(sub.toLowerCase()))) { $el = $(subClassSpanList[i]); break; } } if ($el.hasClass("active")) { $("._class_feature").show(); $(".subclass-prefix").show(); $el.removeClass("active"); return; } $("#subclasses .active").removeClass("active"); $el.addClass("active"); $("._class_feature[data-subclass!='"+$el.text().toLowerCase()+"'][data-subclass!='undefined']").hide(); $(".subclass-prefix").hide(); $("._class_feature[data-subclass='"+$el.text().toLowerCase()+"']").show(); }
js/page-classes.js
var tabledefault=""; var classtabledefault =""; let classlist; window.onload = function load() { let jsonURL = "data/classes.json"; let request = new XMLHttpRequest(); request.open('GET', jsonURL, true); request.onload = function() { let data = JSON.parse(this.response); classlist = data.class; tabledefault = $("#stats").html(); statsprofdefault = $("#statsprof").html(); classtabledefault = $("#classtable").html(); for (var i = 0; i < classlist.length; i++) { var curclass = classlist[i]; $("ul.classes").append("<li><a id='"+i+"' href='#"+encodeURI(curclass.name).toLowerCase()+"' title='"+curclass.name+"'><span class='name col-xs-9'>"+curclass.name+"</span><span class='source col-xs-3' title='"+parse_sourceToFull(curclass.source)+"'>"+curclass.source+"</span></a></li>"); } const list = search({ valueNames: ['name', 'source'], listClass: "classes" }); if (window.location.hash.length) { window.onhashchange(); } else $("#listcontainer a").get(0).click(); }; request.send(); } function loadhash (id) { $("#stats").html(tabledefault); $("#statsprof").html(statsprofdefault); $("#classtable").html(classtabledefault); var curclass = classlist[id]; $("th#name").html(curclass.name); $("td#hp div#hitdice span").html("1d"+curclass.hd); $("td#hp div#hp1stlevel span").html(curclass.hd+" + your Constitution modifier"); $("td#hp div#hphigherlevels span").html("1d"+curclass.hd+" (or "+(curclass.hd/2+1)+") + your Constitution modifier per "+curclass.name+" level after 1st"); $("td#prof div#saves span").html(curclass.proficiency); $("tr:has(.slotlabel)").hide(); $("#classtable tr").not(":has(th)").append("<td class='featurebuffer'></td>"); var subclasses = []; for (var i = curclass.autolevel.length-1; i >= 0; i--) { var curlevel = curclass.autolevel[i]; // spell slots and table data if (!curlevel.feature) { if (curlevel.slots) { $("tr:has(.slotlabel)").show(); if (curlevel.slots.__text) curlevel.slots = curlevel.slots.__text; var curslots = curlevel.slots.split(","); if (curslots[0] !== "0" && $("th.slotbuffer").attr("colspan") < 4) { $("#classtable td.border").attr("colspan", parseInt($("#classtable td.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("th.slotlabel").attr("colspan", curslots.length-1); if (curslots.length > 1) $(".featurebuffer").hide(); for (var a = 0; a < curslots.length; a++) { if (curslots[a] === "0") continue; $(".spellslots"+a).show(); $("tr#level"+curlevel._level+" td.spellslots"+a).html(curslots[a]); } } if (curlevel.spellsknown) { if (!$(".spellsknown").length) { $("th.spellslots0").after("<th class='spellsknown newfeature'>Spells Known</th>"); $("td.spellslots0").after("<td class='spellsknown newfeature'></td>"); $("#classtable th.border").attr("colspan", parseInt($("#classtable th.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("tr#level"+curlevel._level+" td.spellsknown").html(curlevel.spellsknown); } if (curlevel.invocationsknown) { if (!$(".invocationsknown").length) { $("th.spellslots5").after("<th class='spellslots newfeature'>Spell Slots</th> <th class='slotlevel newfeature'>Slot Level</th> <th class='invocationsknown newfeature'>Invocations Known</th>"); $("td.spellslots5").after("<td class='spellslots newfeature'></td> <td class='slotlevel newfeature'></td> <td class='invocationsknown newfeature'>Invocations Known</td>"); $("#classtable th.border").attr("colspan", parseInt($("#classtable th.border").attr("colspan"))+3); } $(".spellslots5").hide(); $("tr#level"+curlevel._level+" td.spellslots").html(curlevel.spellslots); $("tr#level"+curlevel._level+" td.slotlevel").html(curlevel.slotlevel); $("tr#level"+curlevel._level+" td.invocationsknown").html(curlevel.invocationsknown); $("tr:has(.slotlabel)").hide(); } if (curlevel.rages) { if (!$(".rages").length) { $("th.spellslots0").before("<th class='rages newfeature'>Rages</th> <th class='ragedamage newfeature'>Rage Damage</th>"); $("td.spellslots0").before("<td class='rages newfeature'></td> <td class='ragedamage newfeature'></td>"); $("#classtable th.border").attr("colspan", parseInt($("#classtable th.border").attr("colspan"))+2); } $("tr#level"+curlevel._level+" td.rages").html(curlevel.rages); $("tr#level"+curlevel._level+" td.ragedamage").html(curlevel.ragedamage); } if (curlevel.martialarts) { if (!$(".kipoints").length) { $("th.pb").after("<th class='martialarts newfeature'>Martial Arts</th> <th class='kipoints newfeature'>Ki Points</th> <th class='unarmoredmovement newfeature'>Unarmored Movement</th>"); $("td.pb").after("<td class='martialarts newfeature'></td> <td class='kipoints newfeature'></td> <td class='unarmoredmovement newfeature'></td>"); $("#classtable td.border").attr("colspan", parseInt($("#classtable td.border").attr("colspan"))+3); $("th.slotbuffer").attr("colspan", $("th.slotbuffer").attr("colspan")+3); } $("tr#level"+curlevel._level+" td.martialarts").html(curlevel.martialarts); $("tr#level"+curlevel._level+" td.kipoints").html(curlevel.kipoints); $("tr#level"+curlevel._level+" td.unarmoredmovement").html(curlevel.unarmoredmovement); } if (curlevel.sneakattack) { if (!$(".sneakattack").length) { $("th.pb").after("<th class='sneakattack newfeature'>Sneak Attack</th>"); $("td.pb").after("<td class='sneakattack newfeature'></td>"); $("#classtable td.border").attr("colspan", parseInt($("#classtable td.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("tr#level"+curlevel._level+" td.sneakattack").html(curlevel.sneakattack); } if (curlevel.sorcerypoints) { if (!$(".sorcerypoints").length) { $("th.pb").after("<th class='sorcerypoints newfeature'>Sorcery Points</th>"); $("td.pb").after("<td class='sorcerypoints newfeature'></td>"); $("#classtable td.border").attr("colspan", parseInt($("#classtable td.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("tr#level"+curlevel._level+" td.sorcerypoints").html(curlevel.sorcerypoints); } if (curlevel.psilimit) { if (!$(".psilimit").length) { $("th.spellslots0").after("<th class='psilimit newfeature'>Psi Limit</th>"); $("td.spellslots0").after("<td class='psilimit newfeature'></td>"); $("#classtable th.border").attr("colspan", parseInt($("#classtable th.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("tr#level"+curlevel._level+" td.psilimit").html(curlevel.psilimit); } if (curlevel.psipoints) { if (!$(".psipoints").length) { $("th.spellslots0").after("<th class='psipoints newfeature'>Psi Points</th>"); $("td.spellslots0").after("<td class='psipoints newfeature'></td>"); $("#classtable th.border").attr("colspan", parseInt($("#classtable th.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("tr#level"+curlevel._level+" td.psipoints").html(curlevel.psipoints); } if (curlevel.disciplinesknown) { if (!$(".disciplinesknown").length) { $("th.spellslots0").after("<th class='disciplinesknown newfeature'>Disciplines Known</th>"); $("td.spellslots0").after("<td class='disciplinesknown newfeature'></td>"); $("#classtable th.border").attr("colspan", parseInt($("#classtable th.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("tr#level"+curlevel._level+" td.disciplinesknown").html(curlevel.disciplinesknown); } if (curlevel.talentsknown) { if (!$(".talentsknown").length) { $("th.spellslots0").after("<th class='talentsknown newfeature'>Talents Known</th>"); $("td.spellslots0").after("<td class='talentsknown newfeature'></td>"); $("#classtable th.border").attr("colspan", parseInt($("#classtable th.border").attr("colspan"))+1); $("th.slotbuffer").attr("colspan", parseInt($("th.slotbuffer").attr("colspan"))+1); } $("tr#level"+curlevel._level+" td.talentsknown").html(curlevel.talentsknown); } // other features } else for (let a = curlevel.feature.length-1; a >= 0; a--) { let curfeature = curlevel.feature[a]; let link = curlevel._level + "_" + a; if (curfeature._optional === "YES") { subclasses.push(curfeature); } let styleClass = ""; let isInlineHeader = curfeature.suboption === "2"; let removeSubclassNamePrefix = curfeature.subclass !== undefined && curfeature.suboption === undefined; let hasSubclassPrefix = curfeature.subclass !== undefined && curfeature.suboption === "1"; if (curfeature.subclass === undefined && curfeature.suboption === undefined) styleClass = "feature"; else if (curfeature.subclass === undefined && curfeature.suboption !== undefined && curfeature._optional === "YES") styleClass = "optionalsubfeature sub" + curfeature.suboption; else if (curfeature.subclass === undefined && curfeature.suboption !== undefined) styleClass = "subfeature sub" + curfeature.suboption; else if (curfeature.subclass !== undefined && curfeature.suboption === undefined) styleClass = "subclassfeature"; else if (curfeature.subclass !== undefined && curfeature.suboption !== undefined) styleClass = "subclasssubfeature sub" + curfeature.suboption; if (curfeature.name === "Starting Proficiencies") { $("td#prof div#armor span").html(curfeature.text[1].split(":")[1]); $("td#prof div#weapons span").html(curfeature.text[2].split(":")[1]); $("td#prof div#tools span").html(curfeature.text[3].split(":")[1]); $("td#prof div#skills span").html(curfeature.text[4].split(":")[1]); continue; } if (curfeature.name === "Starting Equipment") { $("#equipment div").html("<p>"+curfeature.text.join("</p><p>")); continue; } // write out list to class table var multifeature = ""; if (curlevel.feature.length !== 1 && a !== 0) multifeature = ", "; let featureSpan = document.createElement('span'); featureSpan.setAttribute('data-link', link); featureSpan.onclick = function() {scrollToFeature(featureSpan.getAttribute('data-link'))}; featureSpan.innerHTML = curfeature.name; if (curfeature._optional !== "YES" && curfeature.suboption === undefined) $("tr#level"+curlevel._level+" td.features").prepend(featureSpan).prepend(multifeature); // display features in bottom section var dataua = (curfeature.subclass !== undefined && curfeature.subclass.indexOf(" (UA)") !== -1) ? "true" : "false"; let subclassPrefix = hasSubclassPrefix ? "<span class='subclass-prefix'>" + curfeature.subclass.split(": ")[1] +": </span>" : ""; let dataSubclass = curfeature.subclass === undefined ? undefined : curfeature.subclass.toLowerCase(); if (isInlineHeader) { let namePart = curfeature.name === undefined ? null : "<span id='feature" + link + "' class='inline-header'>" + subclassPrefix + curfeature.name + ".</span> "; $("#features").after("<tr><td colspan='6' class='_class_feature " + styleClass + "' data-subclass='" + dataSubclass + "' data-ua='" + dataua + "'>" + utils_combineText(curfeature.text, "p", namePart) + "</td></tr>"); } else { let namePart = curfeature.name === undefined ? "" : "<strong id='feature" + link + "'>" + subclassPrefix + (removeSubclassNamePrefix ? curfeature.name.split(": ")[1] : curfeature.name) + "</strong>"; let prerequisitePart = curfeature.prerequisite === undefined ? "" : "<p class='prerequisite'>Prerequisite: " + curfeature.prerequisite + "</p>"; $("#features").after("<tr><td colspan='6' class='_class_feature " + styleClass + "' data-subclass='" + dataSubclass + "' data-ua='" + dataua + "'>" + namePart + prerequisitePart + utils_combineText(curfeature.text, "p") + "</td></tr>"); } } } $("td.features, td.slots, td.newfeature").each(function() { if ($(this).html() === "") $(this).html("\u2014") }); $("div#subclasses span").remove(); for (let i = 0; i < subclasses.length; i++) { if (subclasses[i].issubclass === "YES") $("div#subclasses").prepend("<span data-subclass='"+(subclasses[i].name.toLowerCase())+"'><em style='display: none;'>"+subclasses[i].name.split(": ")[0]+": </em><span>"+subclasses[i].name.split(": ")[1]+"</span></span>"); } $("#subclasses > span").sort(asc_sort).appendTo("#subclasses"); $("#subclasses > span").click(function() { const name = $(this).children("span").text() if ($(this).hasClass("active")) window.location.hash = window.location.hash.replace(/\,.*/, "").toLowerCase() else window.location.hash = window.location.hash.replace(/\,.*|$/, "," + encodeURIComponent(name).replace("'", "%27")).toLowerCase() }); return; } function scrollToFeature(ele) { let goTo = document.getElementById("feature"+ele); goTo.scrollIntoView(); } function loadsub(sub) { let subClassSpanList = document.getElementById("subclasses").getElementsByTagName("span"); let $el; for (let i = 0; i < subClassSpanList.length; ++i) { if (subClassSpanList[i].getAttribute('data-subclass') !== undefined && subClassSpanList[i].getAttribute('data-subclass') !== null && subClassSpanList[i].getAttribute('data-subclass').includes(decodeURIComponent(sub.toLowerCase()))) { $el = $(subClassSpanList[i]); break; } } if ($el.hasClass("active")) { $("._class_feature").show(); $(".subclass-prefix").show(); $el.removeClass("active"); return; } $("#subclasses .active").removeClass("active"); $el.addClass("active"); $("._class_feature[data-subclass!='"+$el.text().toLowerCase()+"'][data-subclass!='undefined']").hide(); $(".subclass-prefix").hide(); $("._class_feature[data-subclass='"+$el.text().toLowerCase()+"']").show(); }
iOS fix, maybe
js/page-classes.js
iOS fix, maybe
<ide><path>s/page-classes.js <ide> statsprofdefault = $("#statsprof").html(); <ide> classtabledefault = $("#classtable").html(); <ide> <del> for (var i = 0; i < classlist.length; i++) { <add> for (let i = 0; i < classlist.length; i++) { <ide> var curclass = classlist[i]; <ide> $("ul.classes").append("<li><a id='"+i+"' href='#"+encodeURI(curclass.name).toLowerCase()+"' title='"+curclass.name+"'><span class='name col-xs-9'>"+curclass.name+"</span><span class='source col-xs-3' title='"+parse_sourceToFull(curclass.source)+"'>"+curclass.source+"</span></a></li>"); <ide> } <ide> $("#classtable tr").not(":has(th)").append("<td class='featurebuffer'></td>"); <ide> <ide> var subclasses = []; <del> for (var i = curclass.autolevel.length-1; i >= 0; i--) { <add> for (let i = curclass.autolevel.length-1; i >= 0; i--) { <ide> var curlevel = curclass.autolevel[i]; <ide> <ide> // spell slots and table data
Java
apache-2.0
cfdd409d7c7dc417d8b901a412d4cbdce912a556
0
apache/continuum,apache/continuum,apache/continuum
continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/CheckConfigurationAction.java
package org.apache.maven.continuum.web.action; /* * Copyright 2004-2006 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.maven.continuum.configuration.ConfigurationService; /** * @author <a href="mailto:[email protected]">Emmanuel Venisse</a> * @version $Id$ * * @plexus.component * role="com.opensymphony.xwork.Action" * role-hint="checkConfiguration" */ public class CheckConfigurationAction extends ContinuumActionSupport { public String execute() { ConfigurationService configuration = getContinuum().getConfiguration(); if ( ! configuration.isInitialized() ) { return INPUT; } return SUCCESS; } }
removing unused action git-svn-id: 1d22bf2b43db35b985fe5d7437c243537c14eeaa@484760 13f79535-47bb-0310-9956-ffa450edef68
continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/CheckConfigurationAction.java
removing unused action
<ide><path>ontinuum-webapp/src/main/java/org/apache/maven/continuum/web/action/CheckConfigurationAction.java <del>package org.apache.maven.continuum.web.action; <del> <del>/* <del> * Copyright 2004-2006 The Apache Software Foundation. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>import org.apache.maven.continuum.configuration.ConfigurationService; <del> <del>/** <del> * @author <a href="mailto:[email protected]">Emmanuel Venisse</a> <del> * @version $Id$ <del> * <del> * @plexus.component <del> * role="com.opensymphony.xwork.Action" <del> * role-hint="checkConfiguration" <del> */ <del>public class CheckConfigurationAction <del> extends ContinuumActionSupport <del>{ <del> <del> public String execute() <del> { <del> ConfigurationService configuration = getContinuum().getConfiguration(); <del> <del> if ( ! configuration.isInitialized() ) <del> { <del> return INPUT; <del> } <del> <del> return SUCCESS; <del> } <del>}
Java
epl-1.0
922a5f22534f551c01d28c13f862c15d54363fe7
0
jerr/jbossforge-core,D9110/core,oscerd/core,D9110/core,oscerd/core,forge/core,agoncal/core,jerr/jbossforge-core,pplatek/core,forge/core,oscerd/core,jerr/jbossforge-core,pplatek/core,oscerd/core,pplatek/core,ivannov/core,oscerd/core,jerr/jbossforge-core,D9110/core,agoncal/core,agoncal/core,pplatek/core,agoncal/core,oscerd/core,ivannov/core,jerr/jbossforge-core,oscerd/core,jerr/jbossforge-core,agoncal/core,stalep/forge-core,ivannov/core,ivannov/core,jerr/jbossforge-core,ivannov/core,agoncal/core,D9110/core,pplatek/core,ivannov/core,D9110/core,agoncal/core,oscerd/core,forge/core,forge/core,ivannov/core,D9110/core,D9110/core,agoncal/core,stalep/forge-core,D9110/core,agoncal/core,forge/core,oscerd/core,pplatek/core,ivannov/core,pplatek/core,forge/core,ivannov/core,D9110/core,pplatek/core,jerr/jbossforge-core,forge/core,jerr/jbossforge-core,D9110/core,forge/core,pplatek/core,jerr/jbossforge-core,pplatek/core,forge/core,oscerd/core,agoncal/core,forge/core,ivannov/core
/* * JBoss, by Red Hat. * Copyright 2011, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.forge.shell.plugins.builtin; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.UnknownHostException; import java.util.UUID; import java.util.regex.Pattern; import javax.inject.Inject; import org.jboss.forge.project.services.ResourceFactory; import org.jboss.forge.resources.UnknownFileResource; import org.jboss.forge.shell.Shell; import org.jboss.forge.shell.plugins.Alias; import org.jboss.forge.shell.plugins.DefaultCommand; import org.jboss.forge.shell.plugins.Option; import org.jboss.forge.shell.plugins.PipeOut; import org.jboss.forge.shell.plugins.Plugin; import org.jboss.forge.shell.plugins.Topic; import org.jboss.forge.shell.util.PluginUtil; /** * @author Pablo Palazón * @author <a href="mailto:[email protected]">Koen Aers</a> */ @Alias("run-url") @Topic("Shell Environment") public class RunUrlPlugin implements Plugin { private final Shell shell; @Inject private ResourceFactory factory; @Inject public RunUrlPlugin(final Shell shell) { this.shell = shell; } @DefaultCommand public void run(@Option(description = "url...", required = true) final String url, final PipeOut pipeOut, final String... args) throws Exception { String urlPattern = "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; if (Pattern.matches(urlPattern, url)) { try { URL remote = new URL(url); String temporalDir = System.getProperty("java.io.tmpdir"); File tempFile = new File(temporalDir, "temp" + UUID.randomUUID().toString().replace("-", "")); tempFile.createNewFile(); UnknownFileResource tempResource = new UnknownFileResource(factory, tempFile); PluginUtil.downloadFromURL(pipeOut, remote, tempResource); shell.execute(tempFile, args); } catch (UnknownHostException e) { throw e; } catch (IOException e) { throw new RuntimeException("error executing script from url " + url); } } else { throw new RuntimeException("resource must be a url: " + url); } } }
shell/src/main/java/org/jboss/forge/shell/plugins/builtin/RunUrlPlugin.java
/* * JBoss, by Red Hat. * Copyright 2011, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.forge.shell.plugins.builtin; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.UUID; import java.util.regex.Pattern; import javax.inject.Inject; import org.jboss.forge.project.services.ResourceFactory; import org.jboss.forge.resources.UnknownFileResource; import org.jboss.forge.shell.Shell; import org.jboss.forge.shell.plugins.Alias; import org.jboss.forge.shell.plugins.DefaultCommand; import org.jboss.forge.shell.plugins.Option; import org.jboss.forge.shell.plugins.PipeOut; import org.jboss.forge.shell.plugins.Plugin; import org.jboss.forge.shell.plugins.Topic; import org.jboss.forge.shell.util.PluginUtil; /** * @author Pablo Palazón */ @Alias("run-url") @Topic("Shell Environment") public class RunUrlPlugin implements Plugin { private final Shell shell; @Inject private ResourceFactory factory; @Inject public RunUrlPlugin(final Shell shell) { this.shell = shell; } @DefaultCommand public void run(@Option(description = "url...", required = true) final String url, final PipeOut pipeOut, final String... args) throws Exception { String urlPattern = "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; if (Pattern.matches(urlPattern, url)) { try { URL remote = new URL(url); String temporalDir = System.getProperty("java.io.tmpdir"); File tempFile = new File(temporalDir, "temp" + UUID.randomUUID().toString().replace("-", "")); tempFile.createNewFile(); UnknownFileResource tempResource = new UnknownFileResource(factory, tempFile); PluginUtil.downloadFromURL(pipeOut, remote, tempResource); shell.execute(tempFile, args); } catch (IOException e) { throw new RuntimeException("error executing script from url " + url); } } else { throw new RuntimeException("resource must be a url: " + url); } } }
testRunScriptNotHostHttpUrl in RunUrlPluginTest Fails
shell/src/main/java/org/jboss/forge/shell/plugins/builtin/RunUrlPlugin.java
testRunScriptNotHostHttpUrl in RunUrlPluginTest Fails
<ide><path>hell/src/main/java/org/jboss/forge/shell/plugins/builtin/RunUrlPlugin.java <ide> import java.io.File; <ide> import java.io.IOException; <ide> import java.net.URL; <add>import java.net.UnknownHostException; <ide> import java.util.UUID; <ide> import java.util.regex.Pattern; <ide> <ide> <ide> /** <ide> * @author Pablo Palazón <add> * @author <a href="mailto:[email protected]">Koen Aers</a> <ide> */ <ide> @Alias("run-url") <ide> @Topic("Shell Environment") <ide> PluginUtil.downloadFromURL(pipeOut, remote, tempResource); <ide> shell.execute(tempFile, args); <ide> } <add> catch (UnknownHostException e) { <add> throw e; <add> } <ide> catch (IOException e) <ide> { <ide> throw new RuntimeException("error executing script from url " + url);
Java
apache-2.0
8a4f07c4d26c1c941dc6280f5002d1421925c5d9
0
rsynek/droolsjbpm-knowledge,reynoldsm88/droolsjbpm-knowledge,Multi-Support/droolsjbpm-knowledge,psiroky/droolsjbpm-knowledge,winklerm/drools,bernardator/droolsjbpm-knowledge,droolsjbpm/droolsjbpm-knowledge,Multi-Support/droolsjbpm-knowledge,manstis/drools,reynoldsm88/droolsjbpm-knowledge,rsynek/droolsjbpm-knowledge,droolsjbpm/droolsjbpm-knowledge,mrietveld/droolsjbpm-knowledge,winklerm/drools,manstis/drools,winklerm/drools,sutaakar/droolsjbpm-knowledge,manstis/drools,manstis/drools,mswiderski/droolsjbpm-knowledge,bernardator/droolsjbpm-knowledge,manstis/drools,winklerm/drools,sotty/droolsjbpm-knowledge,sutaakar/droolsjbpm-knowledge,winklerm/drools,sotty/droolsjbpm-knowledge
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.util; import java.io.IOException; import java.util.Dictionary; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; import org.drools.KnowledgeBaseFactoryService; import org.drools.Service; import org.drools.SystemEventListener; import org.drools.SystemEventListenerService; import org.drools.builder.KnowledgeBuilderFactoryService; import org.drools.io.ResourceFactoryService; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.component.ComponentContext; /** * This is an internal class, not for public consumption. * */ public class ServiceRegistryImpl implements ServiceRegistry { private static ServiceRegistry instance; private Map<String, Callable< ? >> registry = new HashMap<String, Callable< ? >>(); private Map<String, Callable< ? >> defaultServices = new HashMap<String, Callable< ? >>(); public static synchronized ServiceRegistry getInstance() { if ( instance == null ) { instance = new ServiceRegistryImpl(); } return ServiceRegistryImpl.instance; } public ServiceRegistryImpl() { init(); } /* (non-Javadoc) * @see org.drools.util.internal.ServiceRegistry#registerLocator(java.lang.String, java.util.concurrent.Callable) */ public synchronized void registerLocator(Class cls, Callable cal) { this.registry.put( cls.getName(), cal ); } /* (non-Javadoc) * @see org.drools.util.internal.ServiceRegistry#unregisterLocator(java.lang.String) */ public synchronized void unregisterLocator(Class cls) { this.registry.remove( cls.getName() ); } synchronized void registerInstance(Service service, Map map) { //this.context.getProperties().put( "org.dr, value ) System.out.println( "regInstance : " + map ); String[] values = ( String[] ) map.get( "objectClass" ); for ( String v : values ) { System.out.println( v ); } // System.out.println( "register : " + service ); this.registry.put( service.getClass().getInterfaces()[0].getName(), new ReturnInstance<Service>( service ) ); // // BundleContext bc = this.context.getBundleContext(); // ServiceReference confAdminRef = bc.getServiceReference( ConfigurationAdmin.class.getName() ); // ConfigurationAdmin admin = ( ConfigurationAdmin ) bc.getService( confAdminRef ); // // try { // Configuration conf = admin.getConfiguration( (String) confAdminRef.getProperty( "service.id" ) ); // Dictionary properties = conf.getProperties(); // properties.put( values[0], "true" ); // conf.update( properties ); // } catch ( IOException e ) { // e.printStackTrace(); // } } /* (non-Javadoc) * @see org.drools.util.internal.ServiceRegistry#unregisterLocator(java.lang.String) */ synchronized void unregisterInstance(Service service, Map map) { System.out.println( "unregister : " + map ); String name = service.getClass().getInterfaces()[0].getName(); this.registry.remove( name ); this.registry.put( name, this.defaultServices.get( name ) ); } // ConfigurationAdmin confAdmin; // synchronized void setConfigurationAdmin(ConfigurationAdmin confAdmin) { // this.confAdmin = confAdmin; // System.out.println( "ConfAdmin : " + this.confAdmin ); // } // // synchronized void unsetConfigurationAdmin(ConfigurationAdmin confAdmin) { // this.confAdmin = null; // } // private ComponentContext context; // void activate(ComponentContext context) { // System.out.println( "reg comp" + context.getProperties() ); // this.context = context; // // // // BundleContext bc = this.context.getBundleContext(); // // ServiceReference confAdminRef = bc.getServiceReference( ConfigurationAdmin.class.getName() ); // ConfigurationAdmin admin = ( ConfigurationAdmin ) bc.getService( confAdminRef ); // System.out.println( "conf admin : " + admin ); // //context. // // log = (LogService) context.locateService("LOG"); // } // void deactivate(ComponentContext context ){ // // } public synchronized <T> T get(Class<T> cls) { Callable< ? > cal = this.registry.get( cls.getName() ); if ( cal != null ) { try { return cls.cast( cal.call() ); } catch ( Exception e ) { throw new IllegalArgumentException( "Unable to instantiate service for Class '" + (cls != null ? cls.getName() : null) + "'", e ); } } else { cal = this.defaultServices.get( cls.getName() ); try { return cls.cast( cal.call() ); } catch ( Exception e ) { throw new IllegalArgumentException( "Unable to instantiate service for Class '" + (cls != null ? cls.getName() : null) + "'", e ); } } } private void init() { addDefault( KnowledgeBuilderFactoryService.class, "org.drools.builder.impl.KnowledgeBuilderFactoryServiceImpl" ); addDefault( KnowledgeBaseFactoryService.class, "org.drools.impl.KnowledgeBaseFactoryServiceImpl" ); addDefault( ResourceFactoryService.class, "org.drools.io.impl.ResourceFactoryServiceImpl" ); addDefault( SystemEventListenerService.class, "org.drools.impl.SystemEventListenerServiceImpl" ); // addDefault( SystemE.class, // "org.drools.io.impl.ResourceFactoryServiceImpl" ); } public synchronized void addDefault(Class cls, String impl) { ReflectionInstantiator<Service> resourceRi = new ReflectionInstantiator<Service>( impl ); defaultServices.put( cls.getName(), resourceRi ); } static class ReflectionInstantiator<V> implements Callable<V> { private String name; public ReflectionInstantiator(String name) { this.name = name; } public V call() throws Exception { return (V) newInstance( name ); } static <T> T newInstance(String name) { try { Class<T> cls = (Class<T>) Class.forName( name ); return cls.newInstance(); } catch ( Exception e2 ) { throw new IllegalArgumentException( "Unable to instantiate '" + name + "'", e2 ); } } } static class ReturnInstance<V> implements Callable<V> { private Service service; public ReturnInstance(Service service) { this.service = service; } public V call() throws Exception { return (V) service; } } }
drools-api/src/main/java/org/drools/util/ServiceRegistryImpl.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.util; import java.io.IOException; import java.util.Dictionary; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; import org.drools.KnowledgeBaseFactoryService; import org.drools.Service; import org.drools.SystemEventListener; import org.drools.SystemEventListenerService; import org.drools.builder.KnowledgeBuilderFactoryService; import org.drools.io.ResourceFactoryService; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.component.ComponentContext; /** * This is an internal class, not for public consumption. * */ public class ServiceRegistryImpl implements ServiceRegistry { private static ServiceRegistry instance; private Map<String, Callable< ? >> registry = new HashMap<String, Callable< ? >>(); private Map<String, Callable< ? >> defaultServices = new HashMap<String, Callable< ? >>(); public static synchronized ServiceRegistry getInstance() { if ( instance == null ) { instance = new ServiceRegistryImpl(); } return ServiceRegistryImpl.instance; } public ServiceRegistryImpl() { init(); } /* (non-Javadoc) * @see org.drools.util.internal.ServiceRegistry#registerLocator(java.lang.String, java.util.concurrent.Callable) */ public synchronized void registerLocator(Class cls, Callable cal) { this.registry.put( cls.getName(), cal ); } /* (non-Javadoc) * @see org.drools.util.internal.ServiceRegistry#unregisterLocator(java.lang.String) */ public synchronized void unregisterLocator(Class cls) { this.registry.remove( cls.getName() ); this.registry.put( cls.getName(), this.defaultServices.get( cls.getName() ) ); } synchronized void registerInstance(Service service, Map map) { //this.context.getProperties().put( "org.dr, value ) System.out.println( "regInstance : " + map ); String[] values = ( String[] ) map.get( "objectClass" ); for ( String v : values ) { System.out.println( v ); } // System.out.println( "register : " + service ); this.registry.put( service.getClass().getInterfaces()[0].getName(), new ReturnInstance<Service>( service ) ); // // BundleContext bc = this.context.getBundleContext(); // ServiceReference confAdminRef = bc.getServiceReference( ConfigurationAdmin.class.getName() ); // ConfigurationAdmin admin = ( ConfigurationAdmin ) bc.getService( confAdminRef ); // // try { // Configuration conf = admin.getConfiguration( (String) confAdminRef.getProperty( "service.id" ) ); // Dictionary properties = conf.getProperties(); // properties.put( values[0], "true" ); // conf.update( properties ); // } catch ( IOException e ) { // e.printStackTrace(); // } } /* (non-Javadoc) * @see org.drools.util.internal.ServiceRegistry#unregisterLocator(java.lang.String) */ synchronized void unregisterInstance(Service service, Map map) { System.out.println( "unregister : " + map ); String name = service.getClass().getInterfaces()[0].getName(); this.registry.remove( name ); this.registry.put( name, this.defaultServices.get( name ) ); } // ConfigurationAdmin confAdmin; // synchronized void setConfigurationAdmin(ConfigurationAdmin confAdmin) { // this.confAdmin = confAdmin; // System.out.println( "ConfAdmin : " + this.confAdmin ); // } // // synchronized void unsetConfigurationAdmin(ConfigurationAdmin confAdmin) { // this.confAdmin = null; // } // private ComponentContext context; // void activate(ComponentContext context) { // System.out.println( "reg comp" + context.getProperties() ); // this.context = context; // // // // BundleContext bc = this.context.getBundleContext(); // // ServiceReference confAdminRef = bc.getServiceReference( ConfigurationAdmin.class.getName() ); // ConfigurationAdmin admin = ( ConfigurationAdmin ) bc.getService( confAdminRef ); // System.out.println( "conf admin : " + admin ); // //context. // // log = (LogService) context.locateService("LOG"); // } // void deactivate(ComponentContext context ){ // // } public synchronized <T> T get(Class<T> cls) { Callable< ? > cal = this.registry.get( cls.getName() ); if ( cal != null ) { try { return cls.cast( cal.call() ); } catch ( Exception e ) { throw new IllegalArgumentException( "Unable to instantiate service for Class '" + (cls != null ? cls.getName() : null) + "'", e ); } } else { cal = this.defaultServices.get( cls.getName() ); try { return cls.cast( cal.call() ); } catch ( Exception e ) { throw new IllegalArgumentException( "Unable to instantiate service for Class '" + (cls != null ? cls.getName() : null) + "'", e ); } } } private void init() { addDefault( KnowledgeBuilderFactoryService.class, "org.drools.builder.impl.KnowledgeBuilderFactoryServiceImpl" ); addDefault( KnowledgeBaseFactoryService.class, "org.drools.impl.KnowledgeBaseFactoryServiceImpl" ); addDefault( ResourceFactoryService.class, "org.drools.io.impl.ResourceFactoryServiceImpl" ); addDefault( SystemEventListenerService.class, "org.drools.impl.SystemEventListenerServiceImpl" ); // addDefault( SystemE.class, // "org.drools.io.impl.ResourceFactoryServiceImpl" ); } public synchronized void addDefault(Class cls, String impl) { ReflectionInstantiator<Service> resourceRi = new ReflectionInstantiator<Service>( impl ); defaultServices.put( cls.getName(), resourceRi ); } static class ReflectionInstantiator<V> implements Callable<V> { private String name; public ReflectionInstantiator(String name) { this.name = name; } public V call() throws Exception { return (V) newInstance( name ); } static <T> T newInstance(String name) { try { Class<T> cls = (Class<T>) Class.forName( name ); return cls.newInstance(); } catch ( Exception e2 ) { throw new IllegalArgumentException( "Unable to instantiate '" + name + "'", e2 ); } } } static class ReturnInstance<V> implements Callable<V> { private Service service; public ReturnInstance(Service service) { this.service = service; } public V call() throws Exception { return (V) service; } } }
JBRULES-2351 OSGi Ready -BPMN2 and DecisionTables providers are now registered properly -ServiceRegistry now does not add defaults to the main registry, instead it uses those as a fallback if nothing is registered. git-svn-id: a243bed356d289ca0d1b6d299a0597bdc4ecaa09@31867 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70
drools-api/src/main/java/org/drools/util/ServiceRegistryImpl.java
JBRULES-2351 OSGi Ready -BPMN2 and DecisionTables providers are now registered properly -ServiceRegistry now does not add defaults to the main registry, instead it uses those as a fallback if nothing is registered.
<ide><path>rools-api/src/main/java/org/drools/util/ServiceRegistryImpl.java <ide> */ <ide> public synchronized void unregisterLocator(Class cls) { <ide> this.registry.remove( cls.getName() ); <del> this.registry.put( cls.getName(), <del> this.defaultServices.get( cls.getName() ) ); <ide> } <ide> <ide> synchronized void registerInstance(Service service, Map map) {
Java
bsd-3-clause
cfb765d3b206cdd460f4350833e8633e5818b494
0
NCIP/nci-term-browser,NCIP/nci-term-browser,NCIP/nci-term-browser,NCIP/nci-term-browser
package gov.nih.nci.evs.browser.servlet; import org.json.*; import gov.nih.nci.evs.browser.utils.*; import gov.nih.nci.evs.browser.common.*; import java.io.*; import java.util.*; import java.net.URI; import javax.servlet.*; import javax.servlet.http.*; import org.apache.log4j.*; import gov.nih.nci.evs.browser.properties.*; import static gov.nih.nci.evs.browser.common.Constants.*; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag; import org.LexGrid.valueSets.ValueSetDefinition; import org.LexGrid.LexBIG.DataModel.Collections.*; import org.LexGrid.LexBIG.DataModel.Core.*; import org.LexGrid.LexBIG.LexBIGService.*; import org.LexGrid.LexBIG.Utility.*; import org.LexGrid.codingSchemes.*; import org.LexGrid.naming.*; import org.LexGrid.LexBIG.Impl.Extensions.GenericExtensions.*; import org.apache.log4j.*; import javax.faces.event.ValueChangeEvent; import org.LexGrid.LexBIG.caCore.interfaces.LexEVSDistributed; import org.lexgrid.valuesets.LexEVSValueSetDefinitionServices; import org.LexGrid.valueSets.ValueSetDefinition; import org.LexGrid.commonTypes.Source; import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference; import org.lexgrid.valuesets.dto.ResolvedValueSetDefinition; import org.LexGrid.LexBIG.Utility.Iterators.ResolvedConceptReferencesIterator; import javax.servlet.ServletOutputStream; import org.LexGrid.concepts.*; import org.lexgrid.valuesets.dto.ResolvedValueSetCodedNodeSet; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType; import org.LexGrid.concepts.Definition; import org.LexGrid.commonTypes.PropertyQualifier; import org.LexGrid.commonTypes.Property; /** * <!-- LICENSE_TEXT_START --> * Copyright 2008,2009 NGIT. This software was developed in conjunction * with the National Cancer Institute, and so to the extent government * employees are co-authors, any rights in such works shall be subject * to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the disclaimer of Article 3, * below. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * 2. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by NGIT and the National * Cancer Institute." If no such end-user documentation is to be * included, this acknowledgment shall appear in the software itself, * wherever such third-party acknowledgments normally appear. * 3. The names "The National Cancer Institute", "NCI" and "NGIT" must * not be used to endorse or promote products derived from this software. * 4. This license does not authorize the incorporation of this software * into any third party proprietary programs. This license does not * authorize the recipient to use any trademarks owned by either NCI * or NGIT * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED * WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE * DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, * NGIT, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * <!-- LICENSE_TEXT_END --> */ /** * @author EVS Team * @version 1.0 * * Modification history * Initial implementation [email protected] * */ public final class AjaxServlet extends HttpServlet { private static Logger _logger = Logger.getLogger(AjaxServlet.class); /** * local constants */ private static final long serialVersionUID = 1L; //private static final int STANDARD_VIEW = 1; //private static final int TERMINOLOGY_VIEW = 2; /** * Validates the Init and Context parameters, configures authentication URL * * @throws ServletException if the init parameters are invalid or any other * problems occur during initialisation */ public void init() throws ServletException { } /** * Route the user to the execute method * * @param request The HTTP request we are processing * @param response The HTTP response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { execute(request, response); } /** * Route the user to the execute method * * @param request The HTTP request we are processing * @param response The HTTP response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a Servlet exception occurs */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { execute(request, response); } private static void debugJSONString(String msg, String jsonString) { boolean debug = false; //DYEE_DEBUG (default: false) if (! debug) return; _logger.debug(Utils.SEPARATOR); if (msg != null && msg.length() > 0) _logger.debug(msg); _logger.debug("jsonString: " + jsonString); _logger.debug("jsonString length: " + jsonString.length()); Utils.debugJSONString(jsonString); } public static void search_tree(HttpServletResponse response, String node_id, String ontology_display_name, String ontology_version) { try { String jsonString = search_tree(node_id, ontology_display_name, ontology_version); if (jsonString == null) return; JSONObject json = new JSONObject(); JSONArray rootsArray = new JSONArray(jsonString); json.put("root_nodes", rootsArray); response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(json.toString()); response.getWriter().flush(); } catch (Exception e) { e.printStackTrace(); } } public static String search_tree(String node_id, String ontology_display_name, String ontology_version) throws Exception { if (node_id == null || ontology_display_name == null) return null; Utils.StopWatch stopWatch = new Utils.StopWatch(); // String max_tree_level_str = // NCItBrowserProperties.getProperty( // NCItBrowserProperties.MAXIMUM_TREE_LEVEL); // int maxLevel = Integer.parseInt(max_tree_level_str); CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (ontology_version != null) versionOrTag.setVersion(ontology_version); String jsonString = CacheController.getTree( ontology_display_name, versionOrTag, node_id); debugJSONString("Section: search_tree", jsonString); _logger.debug("search_tree: " + stopWatch.getResult()); return jsonString; } /** * Process the specified HTTP request, and create the corresponding HTTP * response (or forward to another web component that will create it). * * @param request The HTTP request we are processing * @param response The HTTP response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs */ public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Determine request by attributes String action = request.getParameter("action");// DataConstants.ACTION); String node_id = request.getParameter("ontology_node_id");// DataConstants.ONTOLOGY_NODE_ID); String ontology_display_name = request.getParameter("ontology_display_name");// DataConstants.ONTOLOGY_DISPLAY_NAME); String ontology_version = request.getParameter("version"); if (ontology_version == null) { ontology_version = DataUtils.getVocabularyVersionByTag(ontology_display_name, "PRODUCTION"); } long ms = System.currentTimeMillis(); if (action.equals("expand_tree")) { if (node_id != null && ontology_display_name != null) { System.out.println("(*) EXPAND TREE NODE: " + node_id); response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; try { /* // for HL7 (temporary fix) ontology_display_name = DataUtils.searchFormalName(ontology_display_name); */ nodesArray = CacheController.getInstance().getSubconcepts( ontology_display_name, ontology_version, node_id); if (nodesArray != null) { json.put("nodes", nodesArray); } } catch (Exception e) { } debugJSONString("Section: expand_tree", json.toString()); response.getWriter().write(json.toString()); /* _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); */ } } /* * else if (action.equals("search_tree")) { * * * if (node_id != null && ontology_display_name != null) { * response.setContentType("text/html"); * response.setHeader("Cache-Control", "no-cache"); JSONObject json = * new JSONObject(); try { // testing // JSONArray rootsArray = // * CacheController.getInstance().getPathsToRoots(ontology_display_name, * // null, node_id, true); * * String max_tree_level_str = null; int maxLevel = -1; try { * max_tree_level_str = NCItBrowserProperties .getInstance() * .getProperty( NCItBrowserProperties.MAXIMUM_TREE_LEVEL); maxLevel = * Integer.parseInt(max_tree_level_str); * * } catch (Exception ex) { * * } * * JSONArray rootsArray = CacheController.getInstance() * .getPathsToRoots(ontology_display_name, null, node_id, true, * maxLevel); * * if (rootsArray.length() == 0) { rootsArray = * CacheController.getInstance() .getRootConcepts(ontology_display_name, * null); * * boolean is_root = isRoot(rootsArray, node_id); if (!is_root) { * //rootsArray = null; json.put("dummy_root_nodes", rootsArray); * response.getWriter().write(json.toString()); * response.getWriter().flush(); * * _logger.debug("Run time (milliseconds): " + * (System.currentTimeMillis() - ms)); return; } } * json.put("root_nodes", rootsArray); } catch (Exception e) { * e.printStackTrace(); } * * response.getWriter().write(json.toString()); * response.getWriter().flush(); * * _logger.debug("Run time (milliseconds): " + * (System.currentTimeMillis() - ms)); return; } } */ if (action.equals("search_value_set")) { search_value_set(request, response); } else if (action.equals("create_src_vs_tree")) { create_src_vs_tree(request, response); } else if (action.equals("create_cs_vs_tree")) { create_cs_vs_tree(request, response); } else if (action.equals("search_hierarchy")) { search_hierarchy(request, response, node_id, ontology_display_name, ontology_version); } else if (action.equals("search_tree")) { search_tree(response, node_id, ontology_display_name, ontology_version); } else if (action.equals("build_tree")) { if (ontology_display_name == null) ontology_display_name = CODING_SCHEME_NAME; response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null;// new JSONArray(); try { nodesArray = CacheController.getInstance().getRootConcepts( ontology_display_name, ontology_version); if (nodesArray != null) { json.put("root_nodes", nodesArray); } } catch (Exception e) { e.printStackTrace(); } debugJSONString("Section: build_tree", json.toString()); response.getWriter().write(json.toString()); // response.getWriter().flush(); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); return; } else if (action.equals("build_vs_tree")) { if (ontology_display_name == null) ontology_display_name = CODING_SCHEME_NAME; response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null;// new JSONArray(); try { //HashMap getRootValueSets(String codingSchemeURN) String codingSchemeVersion = null; nodesArray = CacheController.getInstance().getRootValueSets( ontology_display_name, codingSchemeVersion); if (nodesArray != null) { json.put("root_nodes", nodesArray); } } catch (Exception e) { e.printStackTrace(); } response.getWriter().write(json.toString()); //System.out.println(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); return; } else if (action.equals("expand_vs_tree")) { if (node_id != null && ontology_display_name != null) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; try { nodesArray = CacheController.getInstance().getSubValueSets( ontology_display_name, ontology_version, node_id); if (nodesArray != null) { System.out.println("expand_vs_tree nodesArray != null"); json.put("nodes", nodesArray); } else { System.out.println("expand_vs_tree nodesArray == null???"); } } catch (Exception e) { } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); } } else if (action.equals("expand_entire_vs_tree")) { if (node_id != null && ontology_display_name != null) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; try { nodesArray = CacheController.getInstance().getSourceValueSetTree( ontology_display_name, ontology_version, true); if (nodesArray != null) { System.out.println("expand_entire_vs_tree nodesArray != null"); json.put("root_nodes", nodesArray); } else { System.out.println("expand_entire_vs_tree nodesArray == null???"); } } catch (Exception e) { } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); } } else if (action.equals("expand_entire_cs_vs_tree")) { //if (node_id != null && ontology_display_name != null) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; try { nodesArray = CacheController.getInstance().getCodingSchemeValueSetTree( ontology_display_name, ontology_version, true); if (nodesArray != null) { System.out.println("expand_entire_vs_tree nodesArray != null"); json.put("root_nodes", nodesArray); } else { System.out.println("expand_entire_vs_tree nodesArray == null???"); } } catch (Exception e) { } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); //} } else if (action.equals("build_cs_vs_tree")) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null;// new JSONArray(); try { //HashMap getRootValueSets(String codingSchemeURN) String codingSchemeVersion = null; nodesArray = CacheController.getInstance().getRootValueSets(true); if (nodesArray != null) { json.put("root_nodes", nodesArray); } } catch (Exception e) { e.printStackTrace(); } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); return; } else if (action.equals("expand_cs_vs_tree")) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; String vsd_uri = ValueSetHierarchy.getValueSetURI(node_id); node_id = ValueSetHierarchy.getCodingSchemeName(node_id); //if (node_id != null && ontology_display_name != null) { if (node_id != null) { ValueSetDefinition vsd = ValueSetHierarchy.findValueSetDefinitionByURI(vsd_uri); if (vsd == null) { System.out.println("(****) coding scheme name: " + node_id); try { // nodesArray = CacheController.getInstance().getRootValueSets(node_id, null); //nodesArray = CacheController.getInstance().getRootValueSets(node_id, null); //find roots (by source) if (nodesArray != null) { json.put("nodes", nodesArray); } else { System.out.println("expand_vs_tree nodesArray == null???"); } } catch (Exception e) { } } else { try { nodesArray = CacheController.getInstance().getSubValueSets( node_id, null, vsd_uri); if (nodesArray != null) { json.put("nodes", nodesArray); } } catch (Exception e) { } } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); } } else if (action.equals("build_src_vs_tree")) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null;// new JSONArray(); try { //HashMap getRootValueSets(String codingSchemeURN) String codingSchemeVersion = null; nodesArray = //CacheController.getInstance().getRootValueSets(true, true); CacheController.getInstance().build_src_vs_tree(); if (nodesArray != null) { json.put("root_nodes", nodesArray); } } catch (Exception e) { e.printStackTrace(); } response.getWriter().write(json.toString()); //System.out.println(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); return; } else if (action.equals("expand_src_vs_tree")) { if (node_id != null && ontology_display_name != null) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; nodesArray = CacheController.getInstance().expand_src_vs_tree(node_id); if (nodesArray == null) { System.out.println("(*) CacheController returns nodesArray == null"); } try { if (nodesArray != null) { System.out.println("expand_src_vs_tree nodesArray != null"); json.put("nodes", nodesArray); } else { System.out.println("expand_src_vs_tree nodesArray == null???"); } } catch (Exception e) { e.printStackTrace(); } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); } } } private boolean isRoot(JSONArray rootsArray, String code) { for (int i = 0; i < rootsArray.length(); i++) { String node_id = null; try { JSONObject node = rootsArray.getJSONObject(i); node_id = (String) node.get(CacheController.ONTOLOGY_NODE_ID); if (node_id.compareTo(code) == 0) return true; } catch (Exception e) { e.printStackTrace(); } } return false; } private static boolean _debug = false; // DYEE_DEBUG (default: false) private static StringBuffer _debugBuffer = null; public static void println(PrintWriter out, String text) { if (_debug) { _logger.debug("DBG: " + text); _debugBuffer.append(text + "\n"); } out.println(text); } public static void search_hierarchy(HttpServletRequest request, HttpServletResponse response, String node_id, String ontology_display_name, String ontology_version) { Enumeration parameters = request.getParameterNames(); String param = null; while (parameters.hasMoreElements()) { param = (String) parameters.nextElement(); String paramValue = request.getParameter(param); } response.setContentType("text/html"); PrintWriter out = null; try { out = response.getWriter(); } catch (Exception ex) { ex.printStackTrace(); return; } if (_debug) { _debugBuffer = new StringBuffer(); } String localName = DataUtils.getLocalName(ontology_display_name); String formalName = DataUtils.getFormalName(localName); String term_browser_version = DataUtils.getMetadataValue(formalName, ontology_version, "term_browser_version"); String display_name = DataUtils.getMetadataValue(formalName, ontology_version, "display_name"); println(out, ""); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/yahoo-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/event-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/dom-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/animation-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/container-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/connection-min.js\" ></script>"); //println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/autocomplete-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>"); println(out, ""); println(out, ""); println(out, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"); println(out, "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">"); println(out, " <head>"); println(out, " <title>Vocabulary Hierarchy</title>"); println(out, " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />"); println(out, " <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/fonts.css\" />"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/grids.css\" />"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/code.css\" />"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/tree.css\" />"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/search.js\"></script>"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/dropdown.js\"></script>"); println(out, ""); println(out, " <script language=\"JavaScript\">"); println(out, ""); println(out, " var tree;"); println(out, " var nodeIndex;"); println(out, " var rootDescDiv;"); println(out, " var emptyRootDiv;"); println(out, " var treeStatusDiv;"); println(out, " var nodes = [];"); println(out, " var currOpener;"); println(out, ""); println(out, " function load(url,target) {"); println(out, " if (target != '')"); println(out, " target.window.location.href = url;"); println(out, " else"); println(out, " window.location.href = url;"); println(out, " }"); println(out, ""); println(out, " function init() {"); println(out, ""); println(out, " rootDescDiv = new YAHOO.widget.Module(\"rootDesc\", {visible:false} );"); println(out, " resetRootDesc();"); println(out, ""); println(out, " emptyRootDiv = new YAHOO.widget.Module(\"emptyRoot\", {visible:true} );"); println(out, " resetEmptyRoot();"); println(out, ""); println(out, " treeStatusDiv = new YAHOO.widget.Module(\"treeStatus\", {visible:true} );"); println(out, " resetTreeStatus();"); println(out, ""); println(out, " currOpener = opener;"); println(out, " initTree();"); println(out, " }"); println(out, ""); println(out, " function addTreeNode(rootNode, nodeInfo) {"); println(out, " var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); println(out, " var newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); println(out, " var newNode = new YAHOO.widget.TextNode(newNodeData, rootNode, false);"); println(out, " if (nodeInfo.ontology_node_child_count > 0) {"); println(out, " newNode.setDynamicLoad(loadNodeData);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " function buildTree(ontology_node_id, ontology_display_name) {"); println(out, " var handleBuildTreeSuccess = function(o) {"); println(out, " var respTxt = o.responseText;"); println(out, " var respObj = eval('(' + respTxt + ')');"); println(out, " if ( typeof(respObj) != \"undefined\") {"); println(out, " if ( typeof(respObj.root_nodes) != \"undefined\") {"); println(out, " var root = tree.getRoot();"); println(out, " if (respObj.root_nodes.length == 0) {"); println(out, " showEmptyRoot();"); println(out, " }"); println(out, " else {"); println(out, " for (var i=0; i < respObj.root_nodes.length; i++) {"); println(out, " var nodeInfo = respObj.root_nodes[i];"); println(out, " var expand = false;"); println(out, " addTreeNode(root, nodeInfo, expand);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " tree.draw();"); println(out, " }"); println(out, " }"); println(out, " resetTreeStatus();"); println(out, " }"); println(out, ""); println(out, " var handleBuildTreeFailure = function(o) {"); println(out, " resetTreeStatus();"); println(out, " resetEmptyRoot();"); println(out, " alert('responseFailure: ' + o.statusText);"); println(out, " }"); println(out, ""); println(out, " var buildTreeCallback ="); println(out, " {"); println(out, " success:handleBuildTreeSuccess,"); println(out, " failure:handleBuildTreeFailure"); println(out, " };"); println(out, ""); println(out, " if (ontology_display_name!='') {"); println(out, " resetEmptyRoot();"); println(out, ""); println(out, " showTreeLoadingStatus();"); println(out, " var ontology_source = null;"); println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); println(out, " var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " function resetTree(ontology_node_id, ontology_display_name) {"); println(out, ""); println(out, " var handleResetTreeSuccess = function(o) {"); println(out, " var respTxt = o.responseText;"); println(out, " var respObj = eval('(' + respTxt + ')');"); println(out, " if ( typeof(respObj) != \"undefined\") {"); println(out, " if ( typeof(respObj.root_node) != \"undefined\") {"); println(out, " var root = tree.getRoot();"); println(out, " var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";"); println(out, " var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };"); println(out, " var expand = false;"); println(out, " if (respObj.root_node.ontology_node_child_count > 0) {"); println(out, " expand = true;"); println(out, " }"); println(out, " var ontRoot = new YAHOO.widget.TextNode(rootNodeData, root, expand);"); println(out, ""); println(out, " if ( typeof(respObj.child_nodes) != \"undefined\") {"); println(out, " for (var i=0; i < respObj.child_nodes.length; i++) {"); println(out, " var nodeInfo = respObj.child_nodes[i];"); println(out, " addTreeNode(ontRoot, nodeInfo);"); println(out, " }"); println(out, " }"); println(out, " tree.draw();"); println(out, " setRootDesc(respObj.root_node.ontology_node_name, ontology_display_name);"); println(out, " }"); println(out, " }"); println(out, " resetTreeStatus();"); println(out, " }"); println(out, ""); println(out, " var handleResetTreeFailure = function(o) {"); println(out, " resetTreeStatus();"); println(out, " alert('responseFailure: ' + o.statusText);"); println(out, " }"); println(out, ""); println(out, " var resetTreeCallback ="); println(out, " {"); println(out, " success:handleResetTreeSuccess,"); println(out, " failure:handleResetTreeFailure"); println(out, " };"); println(out, " if (ontology_node_id!= '') {"); println(out, " showTreeLoadingStatus();"); println(out, " var ontology_source = null;"); println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); println(out, " var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " function onClickTreeNode(ontology_node_id) {"); out.println(" if (ontology_node_id.indexOf(\"_dot_\") != -1) return;"); println(out, " var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); println(out, " load('/ncitbrowser/ConceptReport.jsp?dictionary='+ ontology_display_name + '&version='+ ontology_version + '&code=' + ontology_node_id, currOpener);"); println(out, " }"); println(out, ""); println(out, " function onClickViewEntireOntology(ontology_display_name) {"); println(out, " var ontology_display_name = document.pg_form.ontology_display_name.value;"); println(out, " tree = new YAHOO.widget.TreeView(\"treecontainer\");"); println(out, " tree.draw();"); println(out, " resetRootDesc();"); println(out, " buildTree('', ontology_display_name);"); println(out, " }"); println(out, ""); println(out, " function initTree() {"); println(out, ""); println(out, " tree = new YAHOO.widget.TreeView(\"treecontainer\");"); println(out, " var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;"); println(out, " var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); println(out, ""); println(out, " if (ontology_node_id == null || ontology_node_id == \"null\")"); println(out, " {"); println(out, " buildTree(ontology_node_id, ontology_display_name);"); println(out, " }"); println(out, " else"); println(out, " {"); println(out, " searchTree(ontology_node_id, ontology_display_name);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " function initRootDesc() {"); println(out, " rootDescDiv.setBody('');"); println(out, " initRootDesc.show();"); println(out, " rootDescDiv.render();"); println(out, " }"); println(out, ""); println(out, " function resetRootDesc() {"); println(out, " rootDescDiv.hide();"); println(out, " rootDescDiv.setBody('');"); println(out, " rootDescDiv.render();"); println(out, " }"); println(out, ""); println(out, " function resetEmptyRoot() {"); println(out, " emptyRootDiv.hide();"); println(out, " emptyRootDiv.setBody('');"); println(out, " emptyRootDiv.render();"); println(out, " }"); println(out, ""); println(out, " function resetTreeStatus() {"); println(out, " treeStatusDiv.hide();"); println(out, " treeStatusDiv.setBody('');"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showEmptyRoot() {"); println(out, " emptyRootDiv.setBody(\"<span class='instruction_text'>No root nodes available.</span>\");"); println(out, " emptyRootDiv.show();"); println(out, " emptyRootDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showNodeNotFound(node_id) {"); println(out, " //emptyRootDiv.setBody(\"<span class='instruction_text'>Concept with code \" + node_id + \" not found in the hierarchy.</span>\");"); println(out, " emptyRootDiv.setBody(\"<span class='instruction_text'>Concept not part of the parent-child hierarchy in this source; check other relationships.</span>\");"); println(out, " emptyRootDiv.show();"); println(out, " emptyRootDiv.render();"); println(out, " }"); println(out, " "); println(out, " function showPartialHierarchy() {"); println(out, " rootDescDiv.setBody(\"<span class='instruction_text'>(Note: This tree only shows partial hierarchy.)</span>\");"); println(out, " rootDescDiv.show();"); println(out, " rootDescDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showTreeLoadingStatus() {"); println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Building tree ...</span>\");"); println(out, " treeStatusDiv.show();"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showTreeDrawingStatus() {"); println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Drawing tree ...</span>\");"); println(out, " treeStatusDiv.show();"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showSearchingTreeStatus() {"); println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Searching tree... Please wait.</span>\");"); println(out, " treeStatusDiv.show();"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showConstructingTreeStatus() {"); println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Constructing tree... Please wait.</span>\");"); println(out, " treeStatusDiv.show();"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); /* println(out, " function loadNodeData(node, fnLoadComplete) {"); println(out, " var id = node.data.id;"); println(out, ""); println(out, " var responseSuccess = function(o)"); println(out, " {"); println(out, " var path;"); println(out, " var dirs;"); println(out, " var files;"); println(out, " var respTxt = o.responseText;"); println(out, " var respObj = eval('(' + respTxt + ')');"); println(out, " var fileNum = 0;"); println(out, " var categoryNum = 0;"); println(out, " if ( typeof(respObj.nodes) != \"undefined\") {"); println(out, " for (var i=0; i < respObj.nodes.length; i++) {"); println(out, " var name = respObj.nodes[i].ontology_node_name;"); println(out, " var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); println(out, " var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); println(out, " var newNode = new YAHOO.widget.TextNode(newNodeData, node, false);"); println(out, " if (respObj.nodes[i].ontology_node_child_count > 0) {"); println(out, " newNode.setDynamicLoad(loadNodeData);"); println(out, " }"); println(out, " }"); println(out, " }"); println(out, " tree.draw();"); println(out, " fnLoadComplete();"); println(out, " }"); */ out.println(" function loadNodeData(node, fnLoadComplete) {"); out.println(" var id = node.data.id;"); out.println(""); out.println(" var responseSuccess = function(o)"); out.println(" {"); out.println(" var path;"); out.println(" var dirs;"); out.println(" var files;"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" var fileNum = 0;"); out.println(" var categoryNum = 0;"); out.println(" var pos = id.indexOf(\"_dot_\");"); out.println(" if ( typeof(respObj.nodes) != \"undefined\") {"); out.println(" if (pos == -1) {"); out.println(" for (var i=0; i < respObj.nodes.length; i++) {"); out.println(" var name = respObj.nodes[i].ontology_node_name;"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); out.println(" var newNode = new YAHOO.widget.TextNode(newNodeData, node, false);"); out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" } else {"); out.println(""); out.println(" var parent = node.parent;"); out.println(" for (var i=0; i < respObj.nodes.length; i++) {"); out.println(" var name = respObj.nodes[i].ontology_node_name;"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); out.println(""); out.println(" var newNode = new YAHOO.widget.TextNode(newNodeData, parent, true);"); out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" tree.removeNode(node,true);"); out.println(" }"); out.println(" }"); out.println(" fnLoadComplete();"); out.println(" }"); println(out, ""); println(out, " var responseFailure = function(o){"); println(out, " alert('responseFailure: ' + o.statusText);"); println(out, " }"); println(out, ""); println(out, " var callback ="); println(out, " {"); println(out, " success:responseSuccess,"); println(out, " failure:responseFailure"); println(out, " };"); println(out, ""); println(out, " var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); //println(out, " var ontology_display_name = " + "\"" + ontology_display_name + "\";"); //println(out, " var ontology_version = " + "\"" + ontology_version + "\";"); println(out, " var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);"); println(out, " }"); println(out, ""); println(out, " function setRootDesc(rootNodeName, ontology_display_name) {"); println(out, " var newDesc = \"<span class='instruction_text'>Root set to <b>\" + rootNodeName + \"</b></span>\";"); println(out, " rootDescDiv.setBody(newDesc);"); println(out, " var footer = \"<a onClick='javascript:onClickViewEntireOntology();' href='#' class='link_text'>view full ontology}</a>\";"); println(out, " rootDescDiv.setFooter(footer);"); println(out, " rootDescDiv.show();"); println(out, " rootDescDiv.render();"); println(out, " }"); println(out, ""); println(out, ""); println(out, " function searchTree(ontology_node_id, ontology_display_name) {"); println(out, ""); println(out, " var root = tree.getRoot();"); //new ViewInHierarchyUtil().printTree(out, ontology_display_name, ontology_version, node_id); new ViewInHierarchyUtils().printTree(out, ontology_display_name, ontology_version, node_id); println(out, " showPartialHierarchy();"); println(out, " tree.draw();"); println(out, " }"); println(out, ""); println(out, ""); println(out, " function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {"); println(out, " var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); println(out, " var newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); println(out, ""); println(out, " var expand = false;"); println(out, " var childNodes = nodeInfo.children_nodes;"); println(out, ""); println(out, " if (childNodes.length > 0) {"); println(out, " expand = true;"); println(out, " }"); println(out, " var newNode = new YAHOO.widget.TextNode(newNodeData, rootNode, expand);"); println(out, " if (nodeInfo.ontology_node_id == ontology_node_id) {"); println(out, " newNode.labelStyle = \"ygtvlabel_highlight\";"); println(out, " }"); println(out, ""); println(out, " if (nodeInfo.ontology_node_id == ontology_node_id) {"); println(out, " newNode.isLeaf = true;"); println(out, " if (nodeInfo.ontology_node_child_count > 0) {"); println(out, " newNode.isLeaf = false;"); println(out, " newNode.setDynamicLoad(loadNodeData);"); println(out, " } else {"); println(out, " tree.draw();"); println(out, " }"); println(out, ""); println(out, " } else {"); println(out, " if (nodeInfo.ontology_node_id != ontology_node_id) {"); println(out, " if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {"); println(out, " newNode.isLeaf = true;"); println(out, " } else if (childNodes.length == 0) {"); println(out, " newNode.setDynamicLoad(loadNodeData);"); println(out, " }"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " tree.draw();"); println(out, " for (var i=0; i < childNodes.length; i++) {"); println(out, " var childnodeInfo = childNodes[i];"); println(out, " addTreeBranch(ontology_node_id, newNode, childnodeInfo);"); println(out, " }"); println(out, " }"); println(out, " YAHOO.util.Event.addListener(window, \"load\", init);"); println(out, ""); println(out, " </script>"); println(out, "</head>"); println(out, "<body>"); println(out, " "); println(out, " <!-- Begin Skip Top Navigation -->"); println(out, " <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>"); println(out, " <!-- End Skip Top Navigation --> "); println(out, " <div id=\"popupContainer\">"); println(out, " <!-- nci popup banner -->"); println(out, " <div class=\"ncipopupbanner\">"); println(out, " <a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\"><img src=\"/ncitbrowser/images/nci-banner-1.gif\" width=\"440\" height=\"39\" border=\"0\" alt=\"National Cancer Institute\" /></a>"); println(out, " <a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\"><img src=\"/ncitbrowser/images/spacer.gif\" width=\"48\" height=\"39\" border=\"0\" alt=\"National Cancer Institute\" class=\"print-header\" /></a>"); println(out, " </div>"); println(out, " <!-- end nci popup banner -->"); println(out, " <div id=\"popupMainArea\">"); println(out, " <a name=\"evs-content\" id=\"evs-content\"></a>"); println(out, " <table class=\"evsLogoBg\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"); println(out, " <tr>"); println(out, " <td valign=\"top\">"); println(out, " <a href=\"http://evs.nci.nih.gov/\" target=\"_blank\" alt=\"Enterprise Vocabulary Services\">"); println(out, " <img src=\"/ncitbrowser/images/evs-popup-logo.gif\" width=\"213\" height=\"26\" alt=\"EVS: Enterprise Vocabulary Services\" title=\"EVS: Enterprise Vocabulary Services\" border=\"0\" />"); println(out, " </a>"); println(out, " </td>"); println(out, " <td valign=\"top\"><div id=\"closeWindow\"><a href=\"javascript:window.close();\"><img src=\"/ncitbrowser/images/thesaurus_close_icon.gif\" width=\"10\" height=\"10\" border=\"0\" alt=\"Close Window\" />&nbsp;CLOSE WINDOW</a></div></td>"); println(out, " </tr>"); println(out, " </table>"); println(out, ""); println(out, ""); String release_date = DataUtils.getVersionReleaseDate(ontology_display_name, ontology_version); if (ontology_display_name.compareTo("NCI Thesaurus") == 0 || ontology_display_name.compareTo("NCI_Thesaurus") == 0) { println(out, " <div>"); println(out, " <img src=\"/ncitbrowser/images/thesaurus_popup_banner.gif\" width=\"612\" height=\"56\" alt=\"NCI Thesaurus\" title=\"\" border=\"0\" />"); println(out, " "); println(out, " "); println(out, " <span class=\"texttitle-blue-rightjust-2\">" + ontology_version + " (Release date: " + release_date + ")</span>"); println(out, " "); println(out, ""); println(out, " </div>"); } else { println(out, " <div>"); println(out, " <img src=\"/ncitbrowser/images/other_popup_banner.gif\" width=\"612\" height=\"56\" alt=\"" + display_name + "\" title=\"\" border=\"0\" />"); println(out, " <div class=\"vocabularynamepopupshort\">" + display_name ); println(out, " "); println(out, " "); println(out, " <span class=\"texttitle-blue-rightjust\">" + ontology_version + " (Release date: " + release_date + ")</span>"); println(out, " "); println(out, " "); println(out, " </div>"); println(out, " </div>"); } println(out, ""); println(out, " <div id=\"popupContentArea\">"); println(out, " <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">"); println(out, " <tr class=\"textbody\">"); println(out, " <td class=\"pageTitle\" align=\"left\">"); println(out, " " + display_name + " Hierarchy"); println(out, " </td>"); println(out, " <td class=\"pageTitle\" align=\"right\">"); println(out, " <font size=\"1\" color=\"red\" align=\"right\">"); println(out, " <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>"); println(out, " </font>"); println(out, " </td>"); println(out, " </tr>"); println(out, " </table>"); if (! ServerMonitorThread.getInstance().isLexEVSRunning()) { println(out, " <div class=\"textbodyredsmall\">" + ServerMonitorThread.getInstance().getMessage() + "</div>"); } else { println(out, " <!-- Tree content -->"); println(out, " <div id=\"rootDesc\">"); println(out, " <div id=\"bd\"></div>"); println(out, " <div id=\"ft\"></div>"); println(out, " </div>"); println(out, " <div id=\"treeStatus\">"); println(out, " <div id=\"bd\"></div>"); println(out, " </div>"); println(out, " <div id=\"emptyRoot\">"); println(out, " <div id=\"bd\"></div>"); println(out, " </div>"); println(out, " <div id=\"treecontainer\"></div>"); } println(out, ""); println(out, " <form id=\"pg_form\">"); println(out, " "); String ontology_node_id_value = HTTPUtils.cleanXSS(node_id); String ontology_display_name_value = HTTPUtils.cleanXSS(ontology_display_name); String ontology_version_value = HTTPUtils.cleanXSS(ontology_version); println(out, " <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"" + ontology_node_id_value + "\" />"); println(out, " <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"" + ontology_display_name_value + "\" />"); //println(out, " <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"" + scheme_value + "\" />"); println(out, " <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"" + ontology_version_value + "\" />"); println(out, ""); println(out, " </form>"); println(out, " <!-- End of Tree control content -->"); println(out, " </div>"); println(out, " </div>"); println(out, " </div>"); println(out, " "); println(out, "</body>"); println(out, "</html>"); if (_debug) { _logger.debug(Utils.SEPARATOR); _logger.debug("VIH HTML:\n" + _debugBuffer); _debugBuffer = null; _logger.debug(Utils.SEPARATOR); } } public static void create_src_vs_tree(HttpServletRequest request, HttpServletResponse response) { create_vs_tree(request, response, Constants.STANDARD_VIEW); } public static void create_cs_vs_tree(HttpServletRequest request, HttpServletResponse response) { String dictionary = (String) request.getParameter("dictionary"); if (!DataUtils.isNull(dictionary)) { String version = (String) request.getParameter("version"); create_vs_tree(request, response, Constants.TERMINOLOGY_VIEW, dictionary, version); } else { create_vs_tree(request, response, Constants.TERMINOLOGY_VIEW); } } public static void create_vs_tree(HttpServletRequest request, HttpServletResponse response, int view) { response.setContentType("text/html"); PrintWriter out = null; try { out = response.getWriter(); } catch (Exception ex) { ex.printStackTrace(); return; } String message = (String) request.getSession().getAttribute("message"); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"); out.println("<html xmlns:c=\"http://java.sun.com/jsp/jstl/core\">"); out.println("<head>"); if (view == Constants.STANDARD_VIEW) { out.println(" <title>NCI Term Browser - Value Set Source View</title>"); } else { out.println(" <title>NCI Term Browser - Value Set Terminology View</title>"); } //out.println(" <title>NCI Thesaurus</title>"); out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"); out.println(""); out.println("<style type=\"text/css\">"); out.println("/*margin and padding on body element"); out.println(" can introduce errors in determining"); out.println(" element position and are not recommended;"); out.println(" we turn them off as a foundation for YUI"); out.println(" CSS treatments. */"); out.println("body {"); out.println(" margin:0;"); out.println(" padding:0;"); out.println("}"); out.println("</style>"); out.println(""); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/fonts/fonts-min.css\" />"); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/treeview/assets/skins/sam/treeview.css\" />"); out.println(""); out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js\"></script>"); //Before(GF31982): out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/treeview/treeview-min.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>"); //GF31982 out.println(""); out.println(""); out.println("<!-- Dependency -->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js\"></script>"); out.println(""); out.println("<!-- Source file -->"); out.println("<!--"); out.println(" If you require only basic HTTP transaction support, use the"); out.println(" connection_core.js file."); out.println("-->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js\"></script>"); out.println(""); out.println("<!--"); out.println(" Use the full connection.js if you require the following features:"); out.println(" - Form serialization."); out.println(" - File Upload using the iframe transport."); out.println(" - Cross-domain(XDR) transactions."); out.println("-->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js\"></script>"); out.println(""); out.println(""); out.println(""); out.println("<!--begin custom header content for this example-->"); out.println("<!--Additional custom style rules for this example:-->"); out.println("<style type=\"text/css\">"); out.println(""); out.println(""); out.println(".ygtvcheck0 { background: url(/ncitbrowser/images/yui/treeview/check0.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(".ygtvcheck1 { background: url(/ncitbrowser/images/yui/treeview/check1.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(".ygtvcheck2 { background: url(/ncitbrowser/images/yui/treeview/check2.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(""); out.println(""); out.println(".ygtv-edit-TaskNode { width: 190px;}"); out.println(".ygtv-edit-TaskNode .ygtvcancel, .ygtv-edit-TextNode .ygtvok { border:none;}"); out.println(".ygtv-edit-TaskNode .ygtv-button-container { float: right;}"); out.println(".ygtv-edit-TaskNode .ygtv-input input{ width: 140px;}"); out.println(".whitebg {"); out.println(" background-color:white;"); out.println("}"); out.println("</style>"); out.println(""); out.println(" <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />"); out.println(" <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />"); out.println(""); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tasknode.js\"></script>"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/search.js\"></script>"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/dropdown.js\"></script>"); out.println(""); out.println(" <script type=\"text/javascript\">"); out.println(""); out.println(" function refresh() {"); out.println(""); out.println(" var selectValueSetSearchOptionObj = document.forms[\"valueSetSearchForm\"].selectValueSetSearchOption;"); out.println(""); out.println(" for (var i=0; i<selectValueSetSearchOptionObj.length; i++) {"); out.println(" if (selectValueSetSearchOptionObj[i].checked) {"); out.println(" selectValueSetSearchOption = selectValueSetSearchOptionObj[i].value;"); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(" window.location.href=\"/ncitbrowser/pages/value_set_source_view.jsf?refresh=1\""); //Before(GF31982) //GF31982(Not Sure): out.println(" window.location.href=\"/ncitbrowser/ajax?action=create_src_vs_tree?refresh=1\""); out.println(" + \"&nav_type=valuesets\" + \"&opt=\"+ selectValueSetSearchOption;"); out.println(""); out.println(" }"); out.println(" </script>"); out.println(""); out.println(" <script language=\"JavaScript\">"); out.println(""); out.println(" var tree;"); out.println(" var nodeIndex;"); out.println(" var nodes = [];"); out.println(""); out.println(" function load(url,target) {"); out.println(" if (target != '')"); out.println(" target.window.location.href = url;"); out.println(" else"); out.println(" window.location.href = url;"); out.println(" }"); out.println(""); out.println(" function init() {"); out.println(" //initTree();"); out.println(" }"); out.println(""); out.println(" //handler for expanding all nodes"); out.println(" YAHOO.util.Event.on(\"expand_all\", \"click\", function(e) {"); out.println(" //expandEntireTree();"); out.println(""); out.println(" tree.expandAll();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for collapsing all nodes"); out.println(" YAHOO.util.Event.on(\"collapse_all\", \"click\", function(e) {"); out.println(" tree.collapseAll();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for checking all nodes"); out.println(" YAHOO.util.Event.on(\"check_all\", \"click\", function(e) {"); out.println(" check_all();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for unchecking all nodes"); out.println(" YAHOO.util.Event.on(\"uncheck_all\", \"click\", function(e) {"); out.println(" uncheck_all();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(""); out.println(""); out.println(" YAHOO.util.Event.on(\"getchecked\", \"click\", function(e) {"); out.println(" //alert(\"Checked nodes: \" + YAHOO.lang.dump(getCheckedNodes()), \"info\", \"example\");"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(""); out.println(" });"); out.println(""); out.println(""); out.println(" function addTreeNode(rootNode, nodeInfo) {"); out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); out.println(""); out.println(" if (nodeInfo.ontology_node_id.indexOf(\"TVS_\") >= 0) {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };"); out.println(" } else {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); out.println(" }"); out.println(""); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, false);"); out.println(" if (nodeInfo.ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function buildTree(ontology_node_id, ontology_display_name) {"); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" }"); out.println(" else {"); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" var expand = false;"); out.println(" //addTreeNode(root, nodeInfo, expand);"); out.println(""); out.println(" addTreeNode(root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" tree.draw();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_src_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function resetTree(ontology_node_id, ontology_display_name) {"); out.println(""); out.println(" var handleResetTreeSuccess = function(o) {"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(" if ( typeof(respObj.root_node) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";"); out.println(" var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };"); out.println(" var expand = false;"); out.println(" if (respObj.root_node.ontology_node_child_count > 0) {"); out.println(" expand = true;"); out.println(" }"); out.println(" var ontRoot = new YAHOO.widget.TaskNode(rootNodeData, root, expand);"); out.println(""); out.println(" if ( typeof(respObj.child_nodes) != \"undefined\") {"); out.println(" for (var i=0; i < respObj.child_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.child_nodes[i];"); out.println(" addTreeNode(ontRoot, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" tree.draw();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleResetTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var resetTreeCallback ="); out.println(" {"); out.println(" success:handleResetTreeSuccess,"); out.println(" failure:handleResetTreeFailure"); out.println(" };"); out.println(" if (ontology_node_id!= '') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function onClickTreeNode(ontology_node_id) {"); out.println(" //alert(\"onClickTreeNode \" + ontology_node_id);"); out.println(" window.location = '/ncitbrowser/pages/value_set_treenode_redirect.jsf?ontology_node_id=' + ontology_node_id;"); out.println(" }"); out.println(""); out.println(""); out.println(" function onClickViewEntireOntology(ontology_display_name) {"); out.println(" var ontology_display_name = document.pg_form.ontology_display_name.value;"); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" tree.draw();"); // out.println(" buildTree('', ontology_display_name);"); out.println(" }"); out.println(""); out.println(" function initTree() {"); out.println(""); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" tree.setNodesProperty('propagateHighlightUp',true);"); out.println(" tree.setNodesProperty('propagateHighlightDown',true);"); out.println(" tree.subscribe('keydown',tree._onKeyDownEvent);"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" tree.subscribe(\"expand\", function(node) {"); out.println(""); out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 39 });"); out.println(""); out.println(" });"); out.println(""); out.println(""); out.println(""); out.println(" tree.subscribe(\"collapse\", function(node) {"); out.println(" //alert(\"Collapsing \" + node.label );"); out.println(""); out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 109 });"); out.println(" });"); out.println(""); out.println(" // By default, trees with TextNodes will fire an event for when the label is clicked:"); out.println(" tree.subscribe(\"checkClick\", function(node) {"); out.println(" //alert(node.data.myNodeId + \" label was checked\");"); out.println(" });"); out.println(""); out.println(""); println(out, " var root = tree.getRoot();"); HashMap value_set_tree_hmap = null; if (view == Constants.STANDARD_VIEW) { value_set_tree_hmap = DataUtils.getSourceValueSetTree(); } else { value_set_tree_hmap = DataUtils.getCodingSchemeValueSetTree(); } TreeItem root = (TreeItem) value_set_tree_hmap.get("<Root>"); //new ValueSetUtils().printTree(out, root); new ValueSetUtils().printTree(out, root, view); String contextPath = request.getContextPath(); String view_str = new Integer(view).toString(); //[#31914] Search option and algorithm in value set search box are not preserved in session. //String option = (String) request.getSession().getAttribute("selectValueSetSearchOption"); //String algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm"); String option = (String) request.getParameter("selectValueSetSearchOption"); if (DataUtils.isNull(option)) { option = (String) request.getSession().getAttribute("selectValueSetSearchOption"); } if (DataUtils.isNull(option)) { option = "Code"; } request.getSession().setAttribute("selectValueSetSearchOption", option); String algorithm = (String) request.getParameter("valueset_search_algorithm"); if (DataUtils.isNull(algorithm)) { algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm"); } if (DataUtils.isNull(algorithm)) { algorithm = "exactMatch"; } request.getSession().setAttribute("valueset_search_algorithm", algorithm); String matchText = (String) request.getParameter("matchText"); if (DataUtils.isNull(matchText)) { matchText = (String) request.getSession().getAttribute("matchText"); } if (DataUtils.isNull(matchText)) { matchText = ""; } else { matchText = matchText.trim(); } request.getSession().setAttribute("matchText", matchText); String option_code = ""; String option_name = ""; if (DataUtils.isNull(option)) { option_code = "checked"; } else { if (option.compareToIgnoreCase("Code") == 0) { option_code = "checked"; } if (option.compareToIgnoreCase("Name") == 0) { option_name = "checked"; } } String algorithm_exactMatch = ""; String algorithm_startsWith = ""; String algorithm_contains = ""; if (DataUtils.isNull(algorithm)) { algorithm_exactMatch = "checked"; } else { if (algorithm.compareToIgnoreCase("exactMatch") == 0) { algorithm_exactMatch = "checked"; } if (algorithm.compareToIgnoreCase("startsWith") == 0) { algorithm_startsWith = "checked"; } if (algorithm.compareToIgnoreCase("contains") == 0) { algorithm_contains = "checked"; } } System.out.println("*** OPTION: " + option); System.out.println("*** ALGORITHM: " + algorithm); System.out.println("*** matchText: " + matchText); System.out.println("AjaxServlet option_code: " + option_code); System.out.println("AjaxServlet option_name: " + option_name); System.out.println("AjaxServlet algorithm_exactMatch: " + algorithm_exactMatch); System.out.println("AjaxServlet algorithm_startsWith: " + algorithm_startsWith); System.out.println("AjaxServlet algorithm_contains: " + algorithm_contains); out.println(""); if (message == null) { out.println(" tree.collapseAll();"); } out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(""); out.println(" function onCheckClick(node) {"); out.println(" YAHOO.log(node.label + \" check was clicked, new state: \" + node.checkState, \"info\", \"example\");"); out.println(" }"); out.println(""); out.println(" function check_all() {"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" topNodes[i].check();"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function uncheck_all() {"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" topNodes[i].uncheck();"); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(" function expand_all() {"); out.println(" //alert(\"expand_all\");"); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" onClickViewEntireOntology(ontology_display_name);"); out.println(" }"); out.println(""); out.println(""); // 0=unchecked, 1=some children checked, 2=all children checked out.println(" // Gets the labels of all of the fully checked nodes"); out.println(" // Could be updated to only return checked leaf nodes by evaluating"); out.println(" // the children collection first."); out.println(" function getCheckedNodes(nodes) {"); out.println(" nodes = nodes || tree.getRoot().children;"); out.println(" checkedNodes = [];"); out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {"); out.println(" var n = nodes[i];"); out.println(" if (n.checkState > 0) { // if we were interested in the nodes that have some but not all children checked"); out.println(" //if (n.checkState == 2) {"); out.println(" checkedNodes.push(n.label); // just using label for simplicity"); out.println(""); out.println(" if (n.hasChildren()) {"); out.println(" checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));"); out.println(" }"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(" var checked_vocabularies = document.forms[\"valueSetSearchForm\"].checked_vocabularies;"); out.println(" checked_vocabularies.value = checkedNodes;"); out.println(""); out.println(" return checkedNodes;"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" function loadNodeData(node, fnLoadComplete) {"); out.println(" var id = node.data.id;"); out.println(""); out.println(" var responseSuccess = function(o)"); out.println(" {"); out.println(" var path;"); out.println(" var dirs;"); out.println(" var files;"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" var fileNum = 0;"); out.println(" var categoryNum = 0;"); out.println(" if ( typeof(respObj.nodes) != \"undefined\") {"); out.println(" for (var i=0; i < respObj.nodes.length; i++) {"); out.println(" var name = respObj.nodes[i].ontology_node_name;"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, node, false);"); out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" tree.draw();"); out.println(" fnLoadComplete();"); out.println(" }"); out.println(""); out.println(" var responseFailure = function(o){"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var callback ="); out.println(" {"); out.println(" success:responseSuccess,"); out.println(" failure:responseFailure"); out.println(" };"); out.println(""); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_src_vs_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);"); out.println(" }"); out.println(""); out.println(""); out.println(" function searchTree(ontology_node_id, ontology_display_name) {"); out.println(""); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(""); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(""); out.println(" if ( typeof(respObj.dummy_root_nodes) != \"undefined\") {"); out.println(" showNodeNotFound(ontology_node_id);"); out.println(" }"); out.println(""); out.println(" else if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" }"); out.println(" else {"); out.println(" showPartialHierarchy();"); out.println(" showConstructingTreeStatus();"); out.println(""); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" //var expand = false;"); out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;//document.pg_form.ontology_source.value;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=search_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(" function expandEntireTree() {"); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" //tree.draw();"); out.println(""); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;"); out.println(""); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(""); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(""); out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(""); out.println(" //alert(respObj.root_nodes.length);"); out.println(""); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" } else {"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" //alert(\"calling addTreeBranch \");"); out.println(""); out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_entire_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {"); out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); out.println(""); out.println(" var newNodeData;"); out.println(" if (ontology_node_id.indexOf(\"TVS_\") >= 0) {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };"); out.println(" } else {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); out.println(" }"); out.println(""); out.println(" var expand = false;"); out.println(" var childNodes = nodeInfo.children_nodes;"); out.println(""); out.println(" if (childNodes.length > 0) {"); out.println(" expand = true;"); out.println(" }"); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, expand);"); out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {"); out.println(" newNode.labelStyle = \"ygtvlabel_highlight\";"); out.println(" }"); out.println(""); out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {"); out.println(" newNode.isLeaf = true;"); out.println(" if (nodeInfo.ontology_node_child_count > 0) {"); out.println(" newNode.isLeaf = false;"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" } else {"); out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(" } else {"); out.println(" if (nodeInfo.ontology_node_id != ontology_node_id) {"); out.println(" if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {"); out.println(" newNode.isLeaf = true;"); out.println(" } else if (childNodes.length == 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" tree.draw();"); out.println(" for (var i=0; i < childNodes.length; i++) {"); out.println(" var childnodeInfo = childNodes[i];"); out.println(" addTreeBranch(ontology_node_id, newNode, childnodeInfo);"); out.println(" }"); out.println(" }"); out.println(" YAHOO.util.Event.addListener(window, \"load\", init);"); out.println(""); out.println(" YAHOO.util.Event.onDOMReady(initTree);"); out.println(""); out.println(""); out.println(" </script>"); out.println(""); out.println("</head>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println("<body onLoad=\"document.forms.valueSetSearchForm.matchText.focus();\">"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/wz_tooltip.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_centerwindow.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_followscroll.js\"></script>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" <!-- Begin Skip Top Navigation -->"); out.println(" <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>"); out.println(" <!-- End Skip Top Navigation -->"); out.println(""); out.println("<!-- nci banner -->"); out.println("<div class=\"ncibanner\">"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/logotype.gif\""); out.println(" width=\"440\" height=\"39\" border=\"0\""); out.println(" alt=\"National Cancer Institute\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/spacer.gif\""); out.println(" width=\"48\" height=\"39\" border=\"0\""); out.println(" alt=\"National Cancer Institute\" class=\"print-header\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.nih.gov\" target=\"_blank\" >"); out.println(" <img src=\"/ncitbrowser/images/tagline_nologo.gif\""); out.println(" width=\"173\" height=\"39\" border=\"0\""); out.println(" alt=\"U.S. National Institutes of Health\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/cancer-gov.gif\""); out.println(" width=\"99\" height=\"39\" border=\"0\""); out.println(" alt=\"www.cancer.gov\"/>"); out.println(" </a>"); out.println("</div>"); out.println("<!-- end nci banner -->"); out.println(""); out.println(" <div class=\"center-page\">"); out.println(" <!-- EVS Logo -->"); out.println("<div>"); out.println(" <img src=\"/ncitbrowser/images/evs-logo-swapped.gif\" alt=\"EVS Logo\""); out.println(" width=\"745\" height=\"26\" border=\"0\""); out.println(" usemap=\"#external-evs\" />"); out.println(" <map id=\"external-evs\" name=\"external-evs\">"); out.println(" <area shape=\"rect\" coords=\"0,0,140,26\""); out.println(" href=\"/ncitbrowser/start.jsf\" target=\"_self\""); out.println(" alt=\"NCI Term Browser\" />"); out.println(" <area shape=\"rect\" coords=\"520,0,745,26\""); out.println(" href=\"http://evs.nci.nih.gov/\" target=\"_blank\""); out.println(" alt=\"Enterprise Vocabulary Services\" />"); out.println(" </map>"); out.println("</div>"); out.println(""); out.println(""); out.println("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"); out.println(" <tr>"); out.println(" <td width=\"5\"></td>"); out.println(" <td><a href=\"/ncitbrowser/pages/multiple_search.jsf?nav_type=terminologies\">"); out.println(" <img name=\"tab_terms\" src=\"/ncitbrowser/images/tab_terms.gif\""); out.println(" border=\"0\" alt=\"Terminologies\" title=\"Terminologies\" /></a></td>"); //Before(GF31982): out.println(" <td><a href=\"/ncitbrowser/pages/value_set_source_view.jsf?nav_type=valuesets\">"); out.println(" <td><a href=\"/ncitbrowser/ajax?action=create_src_vs_tree\">"); //GF31982 out.println(" <img name=\"tab_valuesets\" src=\"/ncitbrowser/images/tab_valuesets_clicked.gif\""); out.println(" border=\"0\" alt=\"Value Sets\" title=\"ValueSets\" /></a></td>"); out.println(" <td><a href=\"/ncitbrowser/pages/mapping_search.jsf?nav_type=mappings\">"); out.println(" <img name=\"tab_map\" src=\"/ncitbrowser/images/tab_map.gif\""); out.println(" border=\"0\" alt=\"Mappings\" title=\"Mappings\" /></a></td>"); out.println(" </tr>"); out.println("</table>"); out.println(""); out.println("<div class=\"mainbox-top\"><img src=\"/ncitbrowser/images/mainbox-top.gif\" width=\"745\" height=\"5\" alt=\"\"/></div>"); out.println("<!-- end EVS Logo -->"); out.println(" <!-- Main box -->"); out.println(" <div id=\"main-area\">"); out.println(""); out.println(" <!-- Thesaurus, banner search area -->"); out.println(" <div class=\"bannerarea\">"); out.println(" <a href=\"/ncitbrowser/start.jsf\" style=\"text-decoration: none;\">"); out.println(" <div class=\"vocabularynamebanner_tb\">"); out.println(" <span class=\"vocabularynamelong_tb\">" + JSPUtils.getApplicationVersionDisplay() + "</span>"); out.println(" </div>"); out.println(" </a>"); out.println(" <div class=\"search-globalnav\">"); out.println(" <!-- Search box -->"); out.println(" <div class=\"searchbox-top\"><img src=\"/ncitbrowser/images/searchbox-top.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Top\" /></div>"); out.println(" <div class=\"searchbox\">"); out.println(""); out.println(""); //out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + + "/ajax?action=saerch_value_set_tree\"> "/pages/value_set_source_view.jsf\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">"); out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + "/ajax?action=search_value_set\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">"); out.println("<input type=\"hidden\" name=\"valueSetSearchForm\" value=\"valueSetSearchForm\" />"); out.println("<input type=\"hidden\" name=\"view\" value=\"" + view_str + "\" />"); out.println(""); out.println(""); out.println(""); out.println(" <input type=\"hidden\" id=\"checked_vocabularies\" name=\"checked_vocabularies\" value=\"\" />"); out.println(""); out.println(""); out.println(""); out.println("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 2px\" >"); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(""); out.println(" <input CLASS=\"searchbox-input-2\""); out.println(" name=\"matchText\""); out.println(" value=\"" + matchText + "\""); out.println(" onFocus=\"active = true\""); out.println(" onBlur=\"active = false\""); out.println(" onkeypress=\"return submitEnter('valueSetSearchForm:valueset_search',event)\""); out.println(" tabindex=\"1\"/>"); out.println(""); out.println(""); out.println(" <input id=\"valueSetSearchForm:valueset_search\" type=\"image\" src=\"/ncitbrowser/images/search.gif\" name=\"valueSetSearchForm:valueset_search\" alt=\"Search Value Sets\" onclick=\"javascript:getCheckedNodes();\" tabindex=\"2\" class=\"searchbox-btn\" /><a href=\"/ncitbrowser/pages/help.jsf#searchhelp\" tabindex=\"3\"><img src=\"/ncitbrowser/images/search-help.gif\" alt=\"Search Help\" style=\"border-width:0;\" class=\"searchbox-btn\" /></a>"); out.println(""); out.println(""); out.println(" </td>"); out.println(" </tr>"); out.println(""); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td>"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 0px\">"); out.println(""); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"exactMatch\" alt=\"Exact Match\" " + algorithm_exactMatch + " tabindex=\"3\">Exact Match&nbsp;"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"startsWith\" alt=\"Begins With\" " + algorithm_startsWith + " tabindex=\"3\">Begins With&nbsp;"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"contains\" alt=\"Contains\" " + algorithm_contains + " tabindex=\"3\">Contains"); out.println(" </td>"); out.println(" </tr>"); out.println(""); out.println(" <tr align=\"left\">"); out.println(" <td height=\"1px\" bgcolor=\"#2F2F5F\" align=\"left\"></td>"); out.println(" </tr>"); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Code\" " + option_code + " alt=\"Code\" tabindex=\"1\" >Code&nbsp;"); out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Name\" " + option_name + " alt=\"Name\" tabindex=\"1\" >Name"); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(" </td>"); out.println(" </tr>"); out.println("</table>"); out.println(" <input type=\"hidden\" name=\"referer\" id=\"referer\" value=\"http%3A%2F%2Flocalhost%3A8080%2Fncitbrowser%2Fpages%2Fresolved_value_set_search_results.jsf\">"); out.println(" <input type=\"hidden\" id=\"nav_type\" name=\"nav_type\" value=\"valuesets\" />"); out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />"); out.println(""); out.println("<input type=\"hidden\" name=\"javax.faces.ViewState\" id=\"javax.faces.ViewState\" value=\"j_id22:j_id23\" />"); out.println("</form>"); out.println(" </div> <!-- searchbox -->"); out.println(""); out.println(" <div class=\"searchbox-bottom\"><img src=\"/ncitbrowser/images/searchbox-bottom.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Bottom\" /></div>"); out.println(" <!-- end Search box -->"); out.println(" <!-- Global Navigation -->"); out.println(""); out.println("<table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">"); out.println(" <tr>"); out.println(" <td align=\"left\" valign=\"bottom\">"); out.println(" <a href=\"#\" onclick=\"javascript:window.open('/ncitbrowser/pages/source_help_info-termbrowser.jsf',"); out.println(" '_blank','top=100, left=100, height=740, width=780, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"13\">"); out.println(" Sources</a>"); out.println(""); //KLO, 022612 out.println(" \r\n"); out.println(" "); out.print( VisitedConceptUtils.getDisplayLink(request, true) ); out.println(" \r\n"); // Visited concepts -- to be implemented. // out.println(" | <A href=\"#\" onmouseover=\"Tip('<ul><li><a href=\'/ncitbrowser/ConceptReport.jsp?dictionary=NCI Thesaurus&version=11.09d&code=C44256\'>Ratio &#40;NCI Thesaurus 11.09d&#41;</a><br></li></ul>',WIDTH, 300, TITLE, 'Visited Concepts', SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, CLOSEBTN, true, CLICKCLOSE, true)\" onmouseout=UnTip() >Visited Concepts</A>"); out.println(" </td>"); out.println(" <td align=\"right\" valign=\"bottom\">"); out.println(" <a href=\""); out.print( request.getContextPath() ); out.println("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n"); out.println(" </td>\r\n"); out.println(" <td width=\"7\"></td>\r\n"); out.println(" </tr>\r\n"); out.println("</table>"); /* out.println(" <a href=\"/ncitbrowser/pages/help.jsf\" tabindex=\"16\">Help</a>"); out.println(" </td>"); out.println(" <td width=\"7\"></td>"); out.println(" </tr>"); out.println("</table>"); */ out.println(" <!-- end Global Navigation -->"); out.println(""); out.println(" </div> <!-- search-globalnav -->"); out.println(" </div> <!-- bannerarea -->"); out.println(""); out.println(" <!-- end Thesaurus, banner search area -->"); out.println(" <!-- Quick links bar -->"); out.println(""); out.println("<div class=\"bluebar\">"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); out.println(" <tr>"); out.println(" <td><div class=\"quicklink-status\">&nbsp;</div></td>"); out.println(" <td>"); out.println(""); /* out.println(" <div id=\"quicklinksholder\">"); out.println(" <ul id=\"quicklinks\""); out.println(" onmouseover=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-active.gif';\""); out.println(" onmouseout=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-inactive.gif';\">"); out.println(" <li>"); out.println(" <a href=\"#\" tabindex=\"-1\"><img src=\"/ncitbrowser/images/quicklinks-inactive.gif\" width=\"162\""); out.println(" height=\"18\" border=\"0\" name=\"quicklinksimg\" alt=\"Quick Links\" />"); out.println(" </a>"); out.println(" <ul>"); out.println(" <li><a href=\"http://evs.nci.nih.gov/\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"Enterprise Vocabulary Services\">EVS Home</a></li>"); out.println(" <li><a href=\"http://localhost/ncimbrowserncimbrowser\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"NCI Metathesaurus\">NCI Metathesaurus Browser</a></li>"); out.println(""); out.println(" <li><a href=\"/ncitbrowser/start.jsf\" tabindex=\"-1\""); out.println(" alt=\"NCI Term Browser\">NCI Term Browser</a></li>"); out.println(" <li><a href=\"http://www.cancer.gov/cancertopics/terminologyresources\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"NCI Terminology Resources\">NCI Terminology Resources</a></li>"); out.println(""); out.println(" <li><a href=\"http://ncitermform.nci.nih.gov/ncitermform/?dictionary=NCI%20Thesaurus\" tabindex=\"-1\" target=\"_blank\" alt=\"Term Suggestion\">Term Suggestion</a></li>"); out.println(""); out.println(""); out.println(" </ul>"); out.println(" </li>"); out.println(" </ul>"); out.println(" </div>"); */ addQuickLink(request, out); out.println(""); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(""); out.println("</div>"); if (! ServerMonitorThread.getInstance().isLexEVSRunning()) { out.println(" <div class=\"redbar\">"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); out.println(" <tr>"); out.println(" <td class=\"lexevs-status\">"); out.println(" " + ServerMonitorThread.getInstance().getMessage()); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(" </div>"); } out.println(" <!-- end Quick links bar -->"); out.println(""); out.println(" <!-- Page content -->"); out.println(" <div class=\"pagecontent\">"); out.println(""); if (message != null) { out.println("\r\n"); out.println(" <p class=\"textbodyred\">"); out.print(message); out.println("</p>\r\n"); out.println(" "); request.getSession().removeAttribute("message"); } out.println("<p class=\"textbody\">"); out.println("View value sets organized by standards category or source terminology."); out.println("Standards categories group the value sets supporting them; all other labels lead to the home pages of actual value sets or source terminologies."); out.println("Search or browse a value set from its home page, or search all value sets at once from this page (very slow) to find which ones contain a particular code or term."); out.println("</p>"); out.println(""); out.println(" <div id=\"popupContentArea\">"); out.println(" <a name=\"evs-content\" id=\"evs-content\"></a>"); out.println(""); out.println(" <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" <tr class=\"textbody\">"); out.println(" <td class=\"textbody\" align=\"left\">"); out.println(""); if (view == Constants.STANDARD_VIEW) { out.println(" Standards View"); out.println(" &nbsp;|"); out.println(" <a href=\"" + contextPath + "/ajax?action=create_cs_vs_tree\">Terminology View</a>"); } else { out.println(" <a href=\"" + contextPath + "/ajax?action=create_src_vs_tree\">Standards View</a>"); out.println(" &nbsp;|"); out.println(" Terminology View"); } out.println(" </td>"); out.println(""); out.println(" <td align=\"right\">"); out.println(" <font size=\"1\" color=\"red\" align=\"right\">"); out.println(" <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>"); out.println(" </font>"); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(""); out.println(" <hr/>"); out.println(""); out.println(""); out.println(""); out.println("<style>"); out.println("#expandcontractdiv {border:1px solid #336600; background-color:#FFFFCC; margin:0 0 .5em 0; padding:0.2em;}"); out.println("#treecontainer { background: #fff }"); out.println("</style>"); out.println(""); out.println(""); out.println("<div id=\"expandcontractdiv\">"); out.println(" <a id=\"expand_all\" href=\"#\">Expand all</a>"); out.println(" <a id=\"collapse_all\" href=\"#\">Collapse all</a>"); out.println(" <a id=\"check_all\" href=\"#\">Check all</a>"); out.println(" <a id=\"uncheck_all\" href=\"#\">Uncheck all</a>"); out.println("</div>"); out.println(""); out.println(""); out.println(""); out.println(" <!-- Tree content -->"); out.println(""); out.println(" <div id=\"treecontainer\" class=\"ygtv-checkbox\"></div>"); out.println(""); out.println(" <form id=\"pg_form\">"); out.println(""); out.println(" <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"null\" />"); //out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"null\" />"); //out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />"); out.println(" </form>"); out.println(""); out.println(""); out.println(" </div> <!-- popupContentArea -->"); out.println(""); out.println(""); out.println("<div class=\"textbody\">"); out.println("<!-- footer -->"); out.println("<div class=\"footer\" style=\"width:720px\">"); out.println(" <ul>"); out.println(" <li><a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\">NCI Home</a> |</li>"); out.println(" <li><a href=\"/ncitbrowser/pages/contact_us.jsf\">Contact Us</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies\" target=\"_blank\" alt=\"National Cancer Institute Policies\">Policies</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies/page3\" target=\"_blank\" alt=\"National Cancer Institute Accessibility\">Accessibility</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies/page6\" target=\"_blank\" alt=\"National Cancer Institute FOIA\">FOIA</a></li>"); out.println(" </ul>"); out.println(" <p>"); out.println(" A Service of the National Cancer Institute<br />"); out.println(" <img src=\"/ncitbrowser/images/external-footer-logos.gif\""); out.println(" alt=\"External Footer Logos\" width=\"238\" height=\"34\" border=\"0\""); out.println(" usemap=\"#external-footer\" />"); out.println(" </p>"); out.println(" <map id=\"external-footer\" name=\"external-footer\">"); out.println(" <area shape=\"rect\" coords=\"0,0,46,34\""); out.println(" href=\"http://www.cancer.gov\" target=\"_blank\""); out.println(" alt=\"National Cancer Institute\" />"); out.println(" <area shape=\"rect\" coords=\"55,1,99,32\""); out.println(" href=\"http://www.hhs.gov/\" target=\"_blank\""); out.println(" alt=\"U.S. Health &amp; Human Services\" />"); out.println(" <area shape=\"rect\" coords=\"103,1,147,31\""); out.println(" href=\"http://www.nih.gov/\" target=\"_blank\""); out.println(" alt=\"National Institutes of Health\" />"); out.println(" <area shape=\"rect\" coords=\"148,1,235,33\""); out.println(" href=\"http://www.usa.gov/\" target=\"_blank\""); out.println(" alt=\"USA.gov\" />"); out.println(" </map>"); out.println("</div>"); out.println("<!-- end footer -->"); out.println("</div>"); out.println(""); out.println(""); out.println(" </div> <!-- pagecontent -->"); out.println(" </div> <!-- main-area -->"); out.println(" <div class=\"mainbox-bottom\"><img src=\"/ncitbrowser/images/mainbox-bottom.gif\" width=\"745\" height=\"5\" alt=\"Mainbox Bottom\" /></div>"); out.println(""); out.println(" </div> <!-- center-page -->"); out.println(""); out.println("</body>"); out.println("</html>"); out.println(""); } public static void search_value_set(HttpServletRequest request, HttpServletResponse response) { System.out.println("(*** AjaxServlet ***) search_value_set ..."); String selectValueSetSearchOption = (String) request.getParameter("selectValueSetSearchOption"); request.getSession().setAttribute("selectValueSetSearchOption", selectValueSetSearchOption); String algorithm = (String) request.getParameter("valueset_search_algorithm"); request.getSession().setAttribute("valueset_search_algorithm", algorithm); System.out.println("(*** AjaxServlet ***) selectValueSetSearchOption ..." + selectValueSetSearchOption); System.out.println("(*** AjaxServlet ***) search_value_set ...algorithm " + algorithm); // check if any checkbox is checked. String contextPath = request.getContextPath(); String view_str = (String) request.getParameter("view"); int view = Integer.parseInt(view_str); String msg = null; request.getSession().removeAttribute("checked_vocabularies"); String checked_vocabularies = (String) request.getParameter("checked_vocabularies"); System.out.println("checked_vocabularies: " + checked_vocabularies); String matchText = (String) request.getParameter("matchText"); if (DataUtils.isNull(matchText)) { matchText = ""; } else { matchText = matchText.trim(); } request.getSession().setAttribute("matchText", matchText); System.out.println("(*** AjaxServlet ***) search_value_set ...matchText " + matchText); String ontology_display_name = (String) request.getParameter("ontology_display_name"); String ontology_version = (String) request.getParameter("ontology_version"); System.out.println("search_value_set ontology_display_name: " + ontology_display_name); System.out.println("search_value_set ontology_version: " + ontology_version); if (matchText.compareTo("") == 0) { msg = "Please enter a search string."; System.out.println(msg); request.getSession().setAttribute("message", msg); if (!DataUtils.isNull(ontology_display_name) && !DataUtils.isNull(ontology_version)) { create_vs_tree(request, response, view, ontology_display_name, ontology_version); } else { create_vs_tree(request, response, view); } return; } if (checked_vocabularies == null || (checked_vocabularies != null && checked_vocabularies.compareTo("") == 0)) { //DYEE msg = "No value set definition is selected."; System.out.println(msg); request.getSession().setAttribute("message", msg); if (!DataUtils.isNull(ontology_display_name) && !DataUtils.isNull(ontology_version)) { create_vs_tree(request, response, view, ontology_display_name, ontology_version); } else { create_vs_tree(request, response, view); } } else { String destination = contextPath + "/pages/value_set_search_results.jsf"; try { String retstr = valueSetSearchAction(request); //KLO, 041312 if (retstr.compareTo("message") == 0) { if (!DataUtils.isNull(ontology_display_name) && !DataUtils.isNull(ontology_version)) { create_vs_tree(request, response, view, ontology_display_name, ontology_version); } else { create_vs_tree(request, response, view); } return; } System.out.println("(*) redirecting to: " + destination); response.sendRedirect(response.encodeRedirectURL(destination)); request.getSession().setAttribute("checked_vocabularies", checked_vocabularies); } catch (Exception ex) { System.out.println("response.sendRedirect failed???"); } } } public static String valueSetSearchAction(HttpServletRequest request) { java.lang.String valueSetDefinitionRevisionId = null; String msg = null; String selectValueSetSearchOption = (String) request.getParameter("selectValueSetSearchOption"); if (DataUtils.isNull(selectValueSetSearchOption)) { selectValueSetSearchOption = "Name"; } request.getSession().setAttribute("selectValueSetSearchOption", selectValueSetSearchOption); String algorithm = (String) request.getParameter("valueset_search_algorithm"); if (DataUtils.isNull(algorithm)) { algorithm = "exactMatch"; } request.getSession().setAttribute("valueset_search_algorithm", algorithm); String checked_vocabularies = (String) request.getParameter("checked_vocabularies"); System.out.println("checked_vocabularies: " + checked_vocabularies); if (checked_vocabularies != null && checked_vocabularies.compareTo("") == 0) { msg = "No value set definition is selected."; System.out.println(msg); request.getSession().setAttribute("message", msg); return "message"; } Vector selected_vocabularies = new Vector(); selected_vocabularies = DataUtils.parseData(checked_vocabularies, ","); System.out.println("selected_vocabularies count: " + selected_vocabularies.size()); String VSD_view = (String) request.getParameter("view"); request.getSession().setAttribute("view", VSD_view); String matchText = (String) request.getParameter("matchText"); Vector v = new Vector(); LexEVSValueSetDefinitionServices vsd_service = null; vsd_service = RemoteServerUtil.getLexEVSValueSetDefinitionServices(); if (matchText != null) matchText = matchText.trim(); if (selectValueSetSearchOption.compareTo("Code") == 0) { String uri = null; try { String versionTag = null;//"PRODUCTION"; if (checked_vocabularies != null) { for (int k=0; k<selected_vocabularies.size(); k++) { String vsd_name = (String) selected_vocabularies.elementAt(k); String vsd_uri = DataUtils.getValueSetDefinitionURIByName(vsd_name); System.out.println("vsd_name: " + vsd_name + " (vsd_uri: " + vsd_uri + ")"); try { //ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(vsd_uri), null); if (vsd_uri != null) { ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(vsd_uri), null); AbsoluteCodingSchemeVersionReference acsvr = vsd_service.isEntityInValueSet(matchText, new URI(vsd_uri), null, versionTag); if (acsvr != null) { String metadata = DataUtils.getValueSetDefinitionMetadata(vsd); if (metadata != null) { v.add(metadata); } } } else { System.out.println("WARNING: Unable to find vsd_uri for " + vsd_name); } } catch (Exception ex) { System.out.println("WARNING: vsd_service.getValueSetDefinition threw exception: " + vsd_name); } } } else { AbsoluteCodingSchemeVersionReferenceList csVersionList = null;//ValueSetHierarchy.getAbsoluteCodingSchemeVersionReferenceList(); List list = vsd_service.listValueSetsWithEntityCode(matchText, null, csVersionList, versionTag); if (list != null) { for (int j=0; j<list.size(); j++) { uri = (String) list.get(j); String vsd_name = DataUtils.valueSetDefiniionURI2Name(uri); if (selected_vocabularies.contains(vsd_name)) { try { ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(uri), null); if (vsd == null) { msg = "Unable to find any value set with URI " + uri + "."; request.getSession().setAttribute("message", msg); return "message"; } String metadata = DataUtils.getValueSetDefinitionMetadata(vsd); if (metadata != null) { v.add(metadata); } } catch (Exception ex) { ex.printStackTrace(); msg = "Unable to find any value set with URI " + uri + "."; request.getSession().setAttribute("message", msg); return "message"; } } } } } request.getSession().setAttribute("matched_vsds", v); if (v.size() == 0) { msg = "No match found."; request.getSession().setAttribute("message", msg); return "message"; } else if (v.size() == 1) { request.getSession().setAttribute("vsd_uri", uri); } return "value_set"; } catch (Exception ex) { ex.printStackTrace(); System.out.println("vsd_service.listValueSetsWithEntityCode throws exceptions???"); } msg = "Unexpected errors encountered; search by code failed."; request.getSession().setAttribute("message", msg); return "message"; } else if (selectValueSetSearchOption.compareTo("Name") == 0) { String uri = null; try { Vector uri_vec = DataUtils.getValueSetURIs(); for (int i=0; i<uri_vec.size(); i++) { uri = (String) uri_vec.elementAt(i); String vsd_name = DataUtils.valueSetDefiniionURI2Name(uri); if (checked_vocabularies == null || selected_vocabularies.contains(vsd_name)) { //System.out.println("Searching " + vsd_name + "..."); AbsoluteCodingSchemeVersionReferenceList csVersionList = null; /* Vector cs_ref_vec = DataUtils.getCodingSchemeReferencesInValueSetDefinition(uri, "PRODUCTION"); if (cs_ref_vec != null) { csVersionList = DataUtils.vector2CodingSchemeVersionReferenceList(cs_ref_vec); } */ ResolvedValueSetCodedNodeSet rvs_cns = null; SortOptionList sortOptions = null; LocalNameList propertyNames = null; CodedNodeSet.PropertyType[] propertyTypes = null; try { System.out.println("URI: " + uri); rvs_cns = vsd_service.getValueSetDefinitionEntitiesForTerm(matchText, algorithm, new URI(uri), csVersionList, null); if (rvs_cns != null) { CodedNodeSet cns = rvs_cns.getCodedNodeSet(); ResolvedConceptReferencesIterator itr = cns.resolve(sortOptions, propertyNames, propertyTypes); if (itr != null && itr.numberRemaining() > 0) { AbsoluteCodingSchemeVersionReferenceList ref_list = rvs_cns.getCodingSchemeVersionRefList(); if (ref_list.getAbsoluteCodingSchemeVersionReferenceCount() > 0) { try { ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(uri), null); if (vsd == null) { msg = "Unable to find any value set with name " + matchText + "."; request.getSession().setAttribute("message", msg); return "message"; } String metadata = DataUtils.getValueSetDefinitionMetadata(vsd); if (metadata != null) { v.add(metadata); } } catch (Exception ex) { ex.printStackTrace(); msg = "Unable to find any value set with name " + matchText + "."; request.getSession().setAttribute("message", msg); return "message"; } } } } } catch (Exception ex) { //System.out.println("WARNING: getValueSetDefinitionEntitiesForTerm throws exception???"); msg = "getValueSetDefinitionEntitiesForTerm throws exception -- search by \"" + matchText + "\" failed. (VSD URI: " + uri + ")"; System.out.println(msg); request.getSession().setAttribute("message", msg); ex.printStackTrace(); return "message"; } } } request.getSession().setAttribute("matched_vsds", v); if (v.size() == 0) { msg = "No match found."; request.getSession().setAttribute("message", msg); return "message"; } else if (v.size() == 1) { request.getSession().setAttribute("vsd_uri", uri); } return "value_set"; } catch (Exception ex) { //ex.printStackTrace(); System.out.println("vsd_service.getValueSetDefinitionEntitiesForTerm throws exceptions???"); } msg = "Unexpected errors encountered; search by name failed."; request.getSession().setAttribute("message", msg); return "message"; } return "value_set"; } public static void create_vs_tree(HttpServletRequest request, HttpServletResponse response, int view, String dictionary, String version) { response.setContentType("text/html"); PrintWriter out = null; try { out = response.getWriter(); } catch (Exception ex) { ex.printStackTrace(); return; } String message = (String) request.getSession().getAttribute("message"); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"); out.println("<html xmlns:c=\"http://java.sun.com/jsp/jstl/core\">"); out.println("<head>"); out.println(" <title>" + dictionary + " value set</title>"); //out.println(" <title>NCI Thesaurus</title>"); out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"); out.println(""); out.println("<style type=\"text/css\">"); out.println("/*margin and padding on body element"); out.println(" can introduce errors in determining"); out.println(" element position and are not recommended;"); out.println(" we turn them off as a foundation for YUI"); out.println(" CSS treatments. */"); out.println("body {"); out.println(" margin:0;"); out.println(" padding:0;"); out.println("}"); out.println("</style>"); out.println(""); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/fonts/fonts-min.css\" />"); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/treeview/assets/skins/sam/treeview.css\" />"); out.println(""); out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>"); out.println(""); out.println(""); out.println("<!-- Dependency -->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js\"></script>"); out.println(""); out.println("<!-- Source file -->"); out.println("<!--"); out.println(" If you require only basic HTTP transaction support, use the"); out.println(" connection_core.js file."); out.println("-->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js\"></script>"); out.println(""); out.println("<!--"); out.println(" Use the full connection.js if you require the following features:"); out.println(" - Form serialization."); out.println(" - File Upload using the iframe transport."); out.println(" - Cross-domain(XDR) transactions."); out.println("-->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js\"></script>"); out.println(""); out.println(""); out.println(""); out.println("<!--begin custom header content for this example-->"); out.println("<!--Additional custom style rules for this example:-->"); out.println("<style type=\"text/css\">"); out.println(""); out.println(""); out.println(".ygtvcheck0 { background: url(/ncitbrowser/images/yui/treeview/check0.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(".ygtvcheck1 { background: url(/ncitbrowser/images/yui/treeview/check1.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(".ygtvcheck2 { background: url(/ncitbrowser/images/yui/treeview/check2.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(""); out.println(""); out.println(".ygtv-edit-TaskNode { width: 190px;}"); out.println(".ygtv-edit-TaskNode .ygtvcancel, .ygtv-edit-TextNode .ygtvok { border:none;}"); out.println(".ygtv-edit-TaskNode .ygtv-button-container { float: right;}"); out.println(".ygtv-edit-TaskNode .ygtv-input input{ width: 140px;}"); out.println(".whitebg {"); out.println(" background-color:white;"); out.println("}"); out.println("</style>"); out.println(""); out.println(" <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />"); out.println(" <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />"); out.println(""); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tasknode.js\"></script>"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/search.js\"></script>"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/dropdown.js\"></script>"); out.println(""); out.println(" <script type=\"text/javascript\">"); out.println(""); out.println(" function refresh() {"); out.println(""); out.println(" var selectValueSetSearchOptionObj = document.forms[\"valueSetSearchForm\"].selectValueSetSearchOption;"); out.println(""); out.println(" for (var i=0; i<selectValueSetSearchOptionObj.length; i++) {"); out.println(" if (selectValueSetSearchOptionObj[i].checked) {"); out.println(" selectValueSetSearchOption = selectValueSetSearchOptionObj[i].value;"); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(" window.location.href=\"/ncitbrowser/pages/value_set_source_view.jsf?refresh=1\""); out.println(" + \"&nav_type=valuesets\" + \"&opt=\"+ selectValueSetSearchOption;"); out.println(""); out.println(" }"); out.println(" </script>"); out.println(""); out.println(" <script language=\"JavaScript\">"); out.println(""); out.println(" var tree;"); out.println(" var nodeIndex;"); out.println(" var nodes = [];"); out.println(""); out.println(" function load(url,target) {"); out.println(" if (target != '')"); out.println(" target.window.location.href = url;"); out.println(" else"); out.println(" window.location.href = url;"); out.println(" }"); out.println(""); out.println(" function init() {"); out.println(" //initTree();"); out.println(" }"); out.println(""); out.println(" //handler for expanding all nodes"); out.println(" YAHOO.util.Event.on(\"expand_all\", \"click\", function(e) {"); out.println(" //expandEntireTree();"); out.println(""); out.println(" tree.expandAll();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for collapsing all nodes"); out.println(" YAHOO.util.Event.on(\"collapse_all\", \"click\", function(e) {"); out.println(" tree.collapseAll();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for checking all nodes"); out.println(" YAHOO.util.Event.on(\"check_all\", \"click\", function(e) {"); out.println(" check_all();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for unchecking all nodes"); out.println(" YAHOO.util.Event.on(\"uncheck_all\", \"click\", function(e) {"); out.println(" uncheck_all();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(""); out.println(""); out.println(" YAHOO.util.Event.on(\"getchecked\", \"click\", function(e) {"); out.println(" //alert(\"Checked nodes: \" + YAHOO.lang.dump(getCheckedNodes()), \"info\", \"example\");"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(""); out.println(" });"); out.println(""); out.println(""); out.println(" function addTreeNode(rootNode, nodeInfo) {"); out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); out.println(""); out.println(" if (nodeInfo.ontology_node_id.indexOf(\"TVS_\") >= 0) {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };"); out.println(" } else {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); out.println(" }"); out.println(""); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, false);"); out.println(" if (nodeInfo.ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function buildTree(ontology_node_id, ontology_display_name) {"); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" }"); out.println(" else {"); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" var expand = false;"); out.println(" //addTreeNode(root, nodeInfo, expand);"); out.println(""); out.println(" addTreeNode(root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" tree.draw();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_src_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function resetTree(ontology_node_id, ontology_display_name) {"); out.println(""); out.println(" var handleResetTreeSuccess = function(o) {"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(" if ( typeof(respObj.root_node) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";"); out.println(" var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };"); out.println(" var expand = false;"); out.println(" if (respObj.root_node.ontology_node_child_count > 0) {"); out.println(" expand = true;"); out.println(" }"); out.println(" var ontRoot = new YAHOO.widget.TaskNode(rootNodeData, root, expand);"); out.println(""); out.println(" if ( typeof(respObj.child_nodes) != \"undefined\") {"); out.println(" for (var i=0; i < respObj.child_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.child_nodes[i];"); out.println(" addTreeNode(ontRoot, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" tree.draw();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleResetTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var resetTreeCallback ="); out.println(" {"); out.println(" success:handleResetTreeSuccess,"); out.println(" failure:handleResetTreeFailure"); out.println(" };"); out.println(" if (ontology_node_id!= '') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function onClickTreeNode(ontology_node_id) {"); out.println(" //alert(\"onClickTreeNode \" + ontology_node_id);"); out.println(" window.location = '/ncitbrowser/pages/value_set_treenode_redirect.jsf?ontology_node_id=' + ontology_node_id;"); out.println(" }"); out.println(""); out.println(""); out.println(" function onClickViewEntireOntology(ontology_display_name) {"); out.println(" var ontology_display_name = document.pg_form.ontology_display_name.value;"); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(" function initTree() {"); out.println(""); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); //out.println(" pre_check();"); out.println(" tree.setNodesProperty('propagateHighlightUp',true);"); out.println(" tree.setNodesProperty('propagateHighlightDown',true);"); out.println(" tree.subscribe('keydown',tree._onKeyDownEvent);"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" tree.subscribe(\"expand\", function(node) {"); out.println(""); out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 39 });"); out.println(""); out.println(" });"); out.println(""); out.println(""); out.println(""); out.println(" tree.subscribe(\"collapse\", function(node) {"); out.println(" //alert(\"Collapsing \" + node.label );"); out.println(""); out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 109 });"); out.println(" });"); out.println(""); out.println(" // By default, trees with TextNodes will fire an event for when the label is clicked:"); out.println(" tree.subscribe(\"checkClick\", function(node) {"); out.println(" //alert(node.data.myNodeId + \" label was checked\");"); out.println(" });"); out.println(""); out.println(""); println(out, " var root = tree.getRoot();"); HashMap value_set_tree_hmap = DataUtils.getCodingSchemeValueSetTree(); TreeItem root = (TreeItem) value_set_tree_hmap.get("<Root>"); new ValueSetUtils().printTree(out, root, Constants.TERMINOLOGY_VIEW, dictionary); //new ValueSetUtils().printTree(out, root, Constants.TERMINOLOGY_VIEW); String contextPath = request.getContextPath(); String view_str = new Integer(view).toString(); //String option = (String) request.getSession().getAttribute("selectValueSetSearchOption"); //String algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm"); String option = (String) request.getParameter("selectValueSetSearchOption"); String algorithm = (String) request.getParameter("valueset_search_algorithm"); String option_code = ""; String option_name = ""; if (DataUtils.isNull(option)) { option_code = "checked"; } else { if (option.compareToIgnoreCase("Code") == 0) { option_code = "checked"; } if (option.compareToIgnoreCase("Name") == 0) { option_name = "checked"; } } String algorithm_exactMatch = ""; String algorithm_startsWith = ""; String algorithm_contains = ""; if (DataUtils.isNull(algorithm)) { algorithm_exactMatch = "checked"; } else { if (algorithm.compareToIgnoreCase("exactMatch") == 0) { algorithm_exactMatch = "checked"; } if (algorithm.compareToIgnoreCase("startsWith") == 0) { algorithm_startsWith = "checked"; } if (algorithm.compareToIgnoreCase("contains") == 0) { algorithm_contains = "checked"; } } out.println(""); if (message == null) { out.println(" tree.collapseAll();"); } out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(""); out.println(" function onCheckClick(node) {"); out.println(" YAHOO.log(node.label + \" check was clicked, new state: \" + node.checkState, \"info\", \"example\");"); out.println(" }"); out.println(""); out.println(" function check_all() {"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" topNodes[i].check();"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function uncheck_all() {"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" topNodes[i].uncheck();"); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(" function expand_all() {"); out.println(" //alert(\"expand_all\");"); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" onClickViewEntireOntology(ontology_display_name);"); out.println(" }"); out.println(""); out.println(" function pre_check() {"); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); //out.println(" alert(ontology_display_name);"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" if (topNodes[i].label == ontology_display_name) {"); out.println(" topNodes[i].check();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); // 0=unchecked, 1=some children checked, 2=all children checked out.println(" // Gets the labels of all of the fully checked nodes"); out.println(" // Could be updated to only return checked leaf nodes by evaluating"); out.println(" // the children collection first."); out.println(" function getCheckedNodes(nodes) {"); out.println(" nodes = nodes || tree.getRoot().children;"); out.println(" checkedNodes = [];"); out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {"); out.println(" var n = nodes[i];"); out.println(" if (n.checkState > 0) { // if we were interested in the nodes that have some but not all children checked"); out.println(" //if (n.checkState == 2) {"); out.println(" checkedNodes.push(n.label); // just using label for simplicity"); out.println(""); out.println(" if (n.hasChildren()) {"); out.println(" checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));"); out.println(" }"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(" var checked_vocabularies = document.forms[\"valueSetSearchForm\"].checked_vocabularies;"); out.println(" checked_vocabularies.value = checkedNodes;"); out.println(""); out.println(" return checkedNodes;"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" function loadNodeData(node, fnLoadComplete) {"); out.println(" var id = node.data.id;"); out.println(""); out.println(" var responseSuccess = function(o)"); out.println(" {"); out.println(" var path;"); out.println(" var dirs;"); out.println(" var files;"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" var fileNum = 0;"); out.println(" var categoryNum = 0;"); out.println(" if ( typeof(respObj.nodes) != \"undefined\") {"); out.println(" for (var i=0; i < respObj.nodes.length; i++) {"); out.println(" var name = respObj.nodes[i].ontology_node_name;"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, node, false);"); out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" tree.draw();"); out.println(" fnLoadComplete();"); out.println(" }"); out.println(""); out.println(" var responseFailure = function(o){"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var callback ="); out.println(" {"); out.println(" success:responseSuccess,"); out.println(" failure:responseFailure"); out.println(" };"); out.println(""); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_src_vs_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);"); out.println(" }"); out.println(""); out.println(""); out.println(" function searchTree(ontology_node_id, ontology_display_name) {"); out.println(""); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(""); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(""); out.println(" if ( typeof(respObj.dummy_root_nodes) != \"undefined\") {"); out.println(" showNodeNotFound(ontology_node_id);"); out.println(" }"); out.println(""); out.println(" else if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" }"); out.println(" else {"); out.println(" showPartialHierarchy();"); out.println(" showConstructingTreeStatus();"); out.println(""); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" //var expand = false;"); out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;//document.pg_form.ontology_source.value;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=search_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(" function expandEntireTree() {"); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" //tree.draw();"); out.println(""); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;"); out.println(""); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(""); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(""); out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(""); out.println(" //alert(respObj.root_nodes.length);"); out.println(""); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" } else {"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" //alert(\"calling addTreeBranch \");"); out.println(""); out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_entire_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {"); out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); out.println(""); out.println(" var newNodeData;"); out.println(" if (ontology_node_id.indexOf(\"TVS_\") >= 0) {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };"); out.println(" } else {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); out.println(" }"); out.println(""); out.println(" var expand = false;"); out.println(" var childNodes = nodeInfo.children_nodes;"); out.println(""); out.println(" if (childNodes.length > 0) {"); out.println(" expand = true;"); out.println(" }"); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, expand);"); out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {"); out.println(" newNode.labelStyle = \"ygtvlabel_highlight\";"); out.println(" }"); out.println(""); out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {"); out.println(" newNode.isLeaf = true;"); out.println(" if (nodeInfo.ontology_node_child_count > 0) {"); out.println(" newNode.isLeaf = false;"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" } else {"); out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(" } else {"); out.println(" if (nodeInfo.ontology_node_id != ontology_node_id) {"); out.println(" if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {"); out.println(" newNode.isLeaf = true;"); out.println(" } else if (childNodes.length == 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" tree.draw();"); out.println(" for (var i=0; i < childNodes.length; i++) {"); out.println(" var childnodeInfo = childNodes[i];"); out.println(" addTreeBranch(ontology_node_id, newNode, childnodeInfo);"); out.println(" }"); out.println(" }"); out.println(" YAHOO.util.Event.addListener(window, \"load\", init);"); out.println(""); out.println(" YAHOO.util.Event.onDOMReady(initTree);"); out.println(""); out.println(""); out.println(" </script>"); out.println(""); out.println("</head>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); //out.println("<body>"); out.println("<body onLoad=\"document.forms.valueSetSearchForm.matchText.focus();\">"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/wz_tooltip.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_centerwindow.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_followscroll.js\"></script>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" <!-- Begin Skip Top Navigation -->"); out.println(" <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>"); out.println(" <!-- End Skip Top Navigation -->"); out.println(""); out.println("<!-- nci banner -->"); out.println("<div class=\"ncibanner\">"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/logotype.gif\""); out.println(" width=\"440\" height=\"39\" border=\"0\""); out.println(" alt=\"National Cancer Institute\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/spacer.gif\""); out.println(" width=\"48\" height=\"39\" border=\"0\""); out.println(" alt=\"National Cancer Institute\" class=\"print-header\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.nih.gov\" target=\"_blank\" >"); out.println(" <img src=\"/ncitbrowser/images/tagline_nologo.gif\""); out.println(" width=\"173\" height=\"39\" border=\"0\""); out.println(" alt=\"U.S. National Institutes of Health\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/cancer-gov.gif\""); out.println(" width=\"99\" height=\"39\" border=\"0\""); out.println(" alt=\"www.cancer.gov\"/>"); out.println(" </a>"); out.println("</div>"); out.println("<!-- end nci banner -->"); out.println(""); out.println(" <div class=\"center-page\">"); out.println(" <!-- EVS Logo -->"); out.println("<div>"); // to be modified out.println(" <img src=\"/ncitbrowser/images/evs-logo-swapped.gif\" alt=\"EVS Logo\""); out.println(" width=\"745\" height=\"26\" border=\"0\""); out.println(" usemap=\"#external-evs\" />"); out.println(" <map id=\"external-evs\" name=\"external-evs\">"); out.println(" <area shape=\"rect\" coords=\"0,0,140,26\""); out.println(" href=\"/ncitbrowser/start.jsf\" target=\"_self\""); out.println(" alt=\"NCI Term Browser\" />"); out.println(" <area shape=\"rect\" coords=\"520,0,745,26\""); out.println(" href=\"http://evs.nci.nih.gov/\" target=\"_blank\""); out.println(" alt=\"Enterprise Vocabulary Services\" />"); out.println(" </map>"); out.println("</div>"); out.println(""); out.println(""); out.println("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"); out.println(" <tr>"); out.println(" <td width=\"5\"></td>"); //to be modified out.println(" <td><a href=\"/ncitbrowser/pages/multiple_search.jsf?nav_type=terminologies\">"); out.println(" <img name=\"tab_terms\" src=\"/ncitbrowser/images/tab_terms_clicked.gif\""); out.println(" border=\"0\" alt=\"Terminologies\" title=\"Terminologies\" /></a></td>"); out.println(" <td><a href=\"/ncitbrowser/ajax?action=create_src_vs_tree\">"); out.println(" <img name=\"tab_valuesets\" src=\"/ncitbrowser/images/tab_valuesets.gif\""); out.println(" border=\"0\" alt=\"Value Sets\" title=\"ValueSets\" /></a></td>"); out.println(" <td><a href=\"/ncitbrowser/pages/mapping_search.jsf?nav_type=mappings\">"); out.println(" <img name=\"tab_map\" src=\"/ncitbrowser/images/tab_map.gif\""); out.println(" border=\"0\" alt=\"Mappings\" title=\"Mappings\" /></a></td>"); out.println(" </tr>"); out.println("</table>"); out.println(""); out.println("<div class=\"mainbox-top\"><img src=\"/ncitbrowser/images/mainbox-top.gif\" width=\"745\" height=\"5\" alt=\"\"/></div>"); out.println("<!-- end EVS Logo -->"); out.println(" <!-- Main box -->"); out.println(" <div id=\"main-area\">"); out.println(""); out.println(" <!-- Thesaurus, banner search area -->"); out.println(" <div class=\"bannerarea\">"); /* out.println(" <a href=\"/ncitbrowser/start.jsf\" style=\"text-decoration: none;\">"); out.println(" <div class=\"vocabularynamebanner_tb\">"); out.println(" <span class=\"vocabularynamelong_tb\">" + JSPUtils.getApplicationVersionDisplay() + "</span>"); out.println(" </div>"); out.println(" </a>"); */ JSPUtils.JSPHeaderInfoMore info = new JSPUtils.JSPHeaderInfoMore(request); String scheme = info.dictionary; String term_browser_version = info.term_browser_version; String display_name = info.display_name; String basePath = request.getContextPath(); /* <a href="/ncitbrowser/pages/home.jsf?version=12.02d" style="text-decoration: none;"> <div class="vocabularynamebanner_ncit"> <span class="vocabularynamelong_ncit">Version: 12.02d (Release date: 2012-02-27-08:00)</span> </div> </a> */ String release_date = DataUtils.getVersionReleaseDate(scheme, version); if (dictionary != null && dictionary.compareTo("NCI Thesaurus") == 0) { out.println("<a href=\"/ncitbrowser/pages/home.jsf?version=" + version + "\" style=\"text-decoration: none;\">"); out.println(" <div class=\"vocabularynamebanner_ncit\">"); out.println(" <span class=\"vocabularynamelong_ncit\">Version: " + version + " (Release date: " + release_date + ")</span>"); out.println(" </div>"); out.println("</a>"); /* out.write("\r\n"); out.write(" <div class=\"banner\"><a href=\""); out.print(basePath); out.write("\"><img src=\""); out.print(basePath); out.write("/images/thesaurus_browser_logo.jpg\" width=\"383\" height=\"117\" alt=\"Thesaurus Browser Logo\" border=\"0\"/></a></div>\r\n"); */ } else { out.write("\r\n"); out.write("\r\n"); out.write(" "); if (version == null) { out.write("\r\n"); out.write(" <a class=\"vocabularynamebanner\" href=\""); out.print(request.getContextPath()); out.write("/pages/vocabulary.jsf?dictionary="); out.print(HTTPUtils.cleanXSS(dictionary)); out.write("\">\r\n"); out.write(" "); } else { out.write("\r\n"); out.write(" <a class=\"vocabularynamebanner\" href=\""); out.print(request.getContextPath()); out.write("/pages/vocabulary.jsf?dictionary="); out.print(HTTPUtils.cleanXSS(dictionary)); out.write("&version="); out.print(HTTPUtils.cleanXSS(version)); out.write("\">\r\n"); out.write(" "); } out.write("\r\n"); out.write(" <div class=\"vocabularynamebanner\">\r\n"); out.write(" <div class=\"vocabularynameshort\" STYLE=\"font-size: "); out.print(HTTPUtils.maxFontSize(display_name)); out.write("px; font-family : Arial\">\r\n"); out.write(" "); out.print(HTTPUtils.cleanXSS(display_name)); out.write("\r\n"); out.write(" </div>\r\n"); out.write(" \r\n"); boolean display_release_date = true; if (release_date == null || release_date.compareTo("") == 0) { display_release_date = false; } if (display_release_date) { out.write("\r\n"); out.write(" <div class=\"vocabularynamelong\">Version: "); out.print(HTTPUtils.cleanXSS(term_browser_version)); out.write(" (Release date: "); out.print(release_date); out.write(")</div>\r\n"); } else { out.write("\r\n"); out.write(" <div class=\"vocabularynamelong\">Version: "); out.print(HTTPUtils.cleanXSS(term_browser_version)); out.write("</div>\r\n"); } out.write(" \r\n"); out.write(" \r\n"); out.write(" </div>\r\n"); out.write(" </a>\r\n"); } out.println(" <div class=\"search-globalnav\">"); out.println(" <!-- Search box -->"); out.println(" <div class=\"searchbox-top\"><img src=\"/ncitbrowser/images/searchbox-top.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Top\" /></div>"); out.println(" <div class=\"searchbox\">"); out.println(""); out.println(""); out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + "/ajax?action=search_value_set\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">"); out.println("<input type=\"hidden\" name=\"valueSetSearchForm\" value=\"valueSetSearchForm\" />"); out.println("<input type=\"hidden\" name=\"view\" value=\"" + view_str + "\" />"); String matchText = (String) request.getSession().getAttribute("matchText"); if (DataUtils.isNull(matchText)) { matchText = ""; } out.println(""); out.println(""); out.println(""); out.println(" <input type=\"hidden\" id=\"checked_vocabularies\" name=\"checked_vocabularies\" value=\"\" />"); out.println(""); out.println(""); out.println(""); out.println("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 2px\" >"); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(""); out.println(" <input CLASS=\"searchbox-input-2\""); out.println(" name=\"matchText\""); out.println(" value=\"" + matchText + "\""); out.println(" onFocus=\"active = true\""); out.println(" onBlur=\"active = false\""); out.println(" onkeypress=\"return submitEnter('valueSetSearchForm:valueset_search',event)\""); out.println(" tabindex=\"1\"/>"); out.println(""); out.println(""); out.println(" <input id=\"valueSetSearchForm:valueset_search\" type=\"image\" src=\"/ncitbrowser/images/search.gif\" name=\"valueSetSearchForm:valueset_search\" alt=\"Search Value Sets\" onclick=\"javascript:getCheckedNodes();\" tabindex=\"2\" class=\"searchbox-btn\" /><a href=\"/ncitbrowser/pages/help.jsf#searchhelp\" tabindex=\"3\"><img src=\"/ncitbrowser/images/search-help.gif\" alt=\"Search Help\" style=\"border-width:0;\" class=\"searchbox-btn\" /></a>"); out.println(""); out.println(""); out.println(" </td>"); out.println(" </tr>"); out.println(""); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td>"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 0px\">"); out.println(""); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"exactMatch\" alt=\"Exact Match\" " + algorithm_exactMatch + " tabindex=\"3\">Exact Match&nbsp;"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"startsWith\" alt=\"Begins With\" " + algorithm_startsWith + " tabindex=\"3\">Begins With&nbsp;"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"contains\" alt=\"Contains\" " + algorithm_contains + " tabindex=\"3\">Contains"); out.println(" </td>"); out.println(" </tr>"); out.println(""); out.println(" <tr align=\"left\">"); out.println(" <td height=\"1px\" bgcolor=\"#2F2F5F\" align=\"left\"></td>"); out.println(" </tr>"); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Code\" " + option_code + " alt=\"Code\" tabindex=\"1\" >Code&nbsp;"); out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Name\" " + option_name + " alt=\"Name\" tabindex=\"1\" >Name"); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(" </td>"); out.println(" </tr>"); out.println("</table>"); out.println(" <input type=\"hidden\" name=\"referer\" id=\"referer\" value=\"http%3A%2F%2Flocalhost%3A8080%2Fncitbrowser%2Fpages%2Fresolved_value_set_search_results.jsf\">"); out.println(" <input type=\"hidden\" id=\"nav_type\" name=\"nav_type\" value=\"valuesets\" />"); out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />"); out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"" + dictionary + "\" />"); out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"" + dictionary + "\" />"); out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"" + version + "\" />"); out.println(""); out.println("<input type=\"hidden\" name=\"javax.faces.ViewState\" id=\"javax.faces.ViewState\" value=\"j_id22:j_id23\" />"); out.println("</form>"); out.println(" </div> <!-- searchbox -->"); out.println(""); out.println(" <div class=\"searchbox-bottom\"><img src=\"/ncitbrowser/images/searchbox-bottom.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Bottom\" /></div>"); out.println(" <!-- end Search box -->"); out.println(" <!-- Global Navigation -->"); out.println(""); /* out.println("<table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">"); out.println(" <tr>"); out.println(" <td align=\"left\" valign=\"bottom\">"); out.println(" <a href=\"#\" onclick=\"javascript:window.open('/ncitbrowser/pages/source_help_info-termbrowser.jsf',"); out.println(" '_blank','top=100, left=100, height=740, width=780, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"13\">"); out.println(" Sources</a>"); out.println(""); out.println(" \r\n"); out.println(" "); out.print( VisitedConceptUtils.getDisplayLink(request, true) ); out.println(" \r\n"); out.println(" </td>"); out.println(" <td align=\"right\" valign=\"bottom\">"); out.println(" <a href=\""); out.print( request.getContextPath() ); out.println("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n"); out.println(" </td>\r\n"); out.println(" <td width=\"7\"></td>\r\n"); out.println(" </tr>\r\n"); out.println("</table>"); */ boolean hasValueSet = ValueSetHierarchy.hasValueSet(scheme); boolean hasMapping = DataUtils.hasMapping(scheme); boolean tree_access_allowed = true; if (DataUtils._vocabulariesWithoutTreeAccessHashSet.contains(scheme)) { tree_access_allowed = false; } boolean vocabulary_isMapping = DataUtils.isMapping(scheme, null); out.write(" <table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">\r\n"); out.write(" <tr>\r\n"); out.write(" <td valign=\"bottom\">\r\n"); out.write(" "); Boolean[] isPipeDisplayed = new Boolean[] { Boolean.FALSE }; out.write("\r\n"); out.write(" "); if (vocabulary_isMapping) { out.write("\r\n"); out.write(" "); out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) ); out.write("\r\n"); out.write(" <a href=\""); out.print(request.getContextPath() ); out.write("/pages/mapping.jsf?dictionary="); out.print(HTTPUtils.cleanXSS(scheme)); out.write("&version="); out.print(version); out.write("\">\r\n"); out.write(" Mapping\r\n"); out.write(" </a>\r\n"); out.write(" "); } else if (tree_access_allowed) { out.write("\r\n"); out.write(" "); out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) ); out.write("\r\n"); out.write(" <a href=\"#\" onclick=\"javascript:window.open('"); out.print(request.getContextPath()); out.write("/pages/hierarchy.jsf?dictionary="); out.print(HTTPUtils.cleanXSS(scheme)); out.write("&version="); out.print(HTTPUtils.cleanXSS(version)); out.write("', '_blank','top=100, left=100, height=740, width=680, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"12\">\r\n"); out.write(" Hierarchy </a>\r\n"); out.write(" "); } out.write(" \r\n"); out.write(" \r\n"); out.write(" \r\n"); out.write(" "); if (hasValueSet) { out.write("\r\n"); out.write(" "); out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) ); out.write("\r\n"); out.write(" <!--\r\n"); out.write(" <a href=\""); out.print( request.getContextPath() ); out.write("/pages/value_set_hierarchy.jsf?dictionary="); out.print(HTTPUtils.cleanXSS(scheme)); out.write("&version="); out.print(HTTPUtils.cleanXSS(version)); out.write("\" tabindex=\"15\">Value Sets</a>\r\n"); out.write(" -->\r\n"); out.write(" <a href=\""); out.print( request.getContextPath() ); out.write("/ajax?action=create_cs_vs_tree&dictionary="); out.print(HTTPUtils.cleanXSS(scheme)); out.write("&version="); out.print(HTTPUtils.cleanXSS(version)); out.write("\" tabindex=\"15\">Value Sets</a>\r\n"); out.write("\r\n"); out.write("\r\n"); out.write(" "); } out.write("\r\n"); out.write(" \r\n"); out.write(" "); if (hasMapping) { out.write("\r\n"); out.write(" "); out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) ); out.write("\r\n"); out.write(" <a href=\""); out.print( request.getContextPath() ); out.write("/pages/cs_mappings.jsf?dictionary="); out.print(HTTPUtils.cleanXSS(scheme)); out.write("&version="); out.print(HTTPUtils.cleanXSS(version)); out.write("\" tabindex=\"15\">Maps</a> \r\n"); out.write(" "); } out.write(" "); out.print( VisitedConceptUtils.getDisplayLink(request, isPipeDisplayed) ); out.write("\r\n"); out.write(" </td>\r\n"); out.write(" <td align=\"right\" valign=\"bottom\">\r\n"); out.write(" <a href=\""); out.print(request.getContextPath()); out.write("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n"); out.write(" </td>\r\n"); out.write(" <td width=\"7\" valign=\"bottom\"></td>\r\n"); out.write(" </tr>\r\n"); out.write(" </table>\r\n"); out.println(" <!-- end Global Navigation -->"); out.println(""); out.println(" </div> <!-- search-globalnav -->"); out.println(" </div> <!-- bannerarea -->"); out.println(""); out.println(" <!-- end Thesaurus, banner search area -->"); out.println(" <!-- Quick links bar -->"); out.println(""); out.println("<div class=\"bluebar\">"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); out.println(" <tr>"); out.println(" <td><div class=\"quicklink-status\">&nbsp;</div></td>"); out.println(" <td>"); out.println(""); /* out.println(" <div id=\"quicklinksholder\">"); out.println(" <ul id=\"quicklinks\""); out.println(" onmouseover=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-active.gif';\""); out.println(" onmouseout=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-inactive.gif';\">"); out.println(" <li>"); out.println(" <a href=\"#\" tabindex=\"-1\"><img src=\"/ncitbrowser/images/quicklinks-inactive.gif\" width=\"162\""); out.println(" height=\"18\" border=\"0\" name=\"quicklinksimg\" alt=\"Quick Links\" />"); out.println(" </a>"); out.println(" <ul>"); out.println(" <li><a href=\"http://evs.nci.nih.gov/\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"Enterprise Vocabulary Services\">EVS Home</a></li>"); out.println(" <li><a href=\"http://localhost/ncimbrowserncimbrowser\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"NCI Metathesaurus\">NCI Metathesaurus Browser</a></li>"); out.println(""); out.println(" <li><a href=\"/ncitbrowser/start.jsf\" tabindex=\"-1\""); out.println(" alt=\"NCI Term Browser\">NCI Term Browser</a></li>"); out.println(" <li><a href=\"http://www.cancer.gov/cancertopics/terminologyresources\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"NCI Terminology Resources\">NCI Terminology Resources</a></li>"); out.println(""); out.println(" <li><a href=\"http://ncitermform.nci.nih.gov/ncitermform/?dictionary=NCI%20Thesaurus\" tabindex=\"-1\" target=\"_blank\" alt=\"Term Suggestion\">Term Suggestion</a></li>"); out.println(""); out.println(""); out.println(" </ul>"); out.println(" </li>"); out.println(" </ul>"); out.println(" </div>"); */ addQuickLink(request, out); out.println(""); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(""); out.println("</div>"); if (! ServerMonitorThread.getInstance().isLexEVSRunning()) { out.println(" <div class=\"redbar\">"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); out.println(" <tr>"); out.println(" <td class=\"lexevs-status\">"); out.println(" " + ServerMonitorThread.getInstance().getMessage()); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(" </div>"); } out.println(" <!-- end Quick links bar -->"); out.println(""); out.println(" <!-- Page content -->"); out.println(" <div class=\"pagecontent\">"); out.println(""); if (message != null) { out.println("\r\n"); out.println(" <p class=\"textbodyred\">"); out.print(message); out.println("</p>\r\n"); out.println(" "); request.getSession().removeAttribute("message"); } // to be modified /* out.println("<p class=\"textbody\">"); out.println("View value sets organized by standards category or source terminology."); out.println("Standards categories group the value sets supporting them; all other labels lead to the home pages of actual value sets or source terminologies."); out.println("Search or browse a value set from its home page, or search all value sets at once from this page (very slow) to find which ones contain a particular code or term."); out.println("</p>"); */ out.println(""); out.println(" <div id=\"popupContentArea\">"); out.println(" <a name=\"evs-content\" id=\"evs-content\"></a>"); out.println(""); out.println(" <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" <tr class=\"textbody\">"); out.println(" <td class=\"textbody\" align=\"left\">"); out.println(""); /* if (view == Constants.STANDARD_VIEW) { out.println(" Standards View"); out.println(" &nbsp;|"); out.println(" <a href=\"" + contextPath + "/ajax?action=create_cs_vs_tree\">Terminology View</a>"); } else { out.println(" <a href=\"" + contextPath + "/ajax?action=create_src_vs_tree\">Standards View</a>"); out.println(" &nbsp;|"); out.println(" Terminology View"); } */ out.println(" </td>"); out.println(""); out.println(" <td align=\"right\">"); out.println(" <font size=\"1\" color=\"red\" align=\"right\">"); out.println(" <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>"); out.println(" </font>"); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(""); out.println(" <hr/>"); out.println(""); out.println(""); out.println(""); out.println("<style>"); out.println("#expandcontractdiv {border:1px solid #336600; background-color:#FFFFCC; margin:0 0 .5em 0; padding:0.2em;}"); out.println("#treecontainer { background: #fff }"); out.println("</style>"); out.println(""); out.println(""); out.println("<div id=\"expandcontractdiv\">"); out.println(" <a id=\"expand_all\" href=\"#\">Expand all</a>"); out.println(" <a id=\"collapse_all\" href=\"#\">Collapse all</a>"); out.println(" <a id=\"check_all\" href=\"#\">Check all</a>"); out.println(" <a id=\"uncheck_all\" href=\"#\">Uncheck all</a>"); out.println("</div>"); out.println(""); out.println(""); out.println(""); out.println(" <!-- Tree content -->"); out.println(""); out.println(" <div id=\"treecontainer\" class=\"ygtv-checkbox\"></div>"); out.println(""); out.println(" <form id=\"pg_form\">"); out.println(""); out.println(" <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"" + dictionary + "\" />"); out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"" + dictionary + "\" />"); out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"" + version + "\" />"); out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />"); out.println(" </form>"); out.println(""); out.println(""); out.println(" </div> <!-- popupContentArea -->"); out.println(""); out.println(""); out.println("<div class=\"textbody\">"); out.println("<!-- footer -->"); out.println("<div class=\"footer\" style=\"width:720px\">"); out.println(" <ul>"); out.println(" <li><a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\">NCI Home</a> |</li>"); out.println(" <li><a href=\"/ncitbrowser/pages/contact_us.jsf\">Contact Us</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies\" target=\"_blank\" alt=\"National Cancer Institute Policies\">Policies</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies/page3\" target=\"_blank\" alt=\"National Cancer Institute Accessibility\">Accessibility</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies/page6\" target=\"_blank\" alt=\"National Cancer Institute FOIA\">FOIA</a></li>"); out.println(" </ul>"); out.println(" <p>"); out.println(" A Service of the National Cancer Institute<br />"); out.println(" <img src=\"/ncitbrowser/images/external-footer-logos.gif\""); out.println(" alt=\"External Footer Logos\" width=\"238\" height=\"34\" border=\"0\""); out.println(" usemap=\"#external-footer\" />"); out.println(" </p>"); out.println(" <map id=\"external-footer\" name=\"external-footer\">"); out.println(" <area shape=\"rect\" coords=\"0,0,46,34\""); out.println(" href=\"http://www.cancer.gov\" target=\"_blank\""); out.println(" alt=\"National Cancer Institute\" />"); out.println(" <area shape=\"rect\" coords=\"55,1,99,32\""); out.println(" href=\"http://www.hhs.gov/\" target=\"_blank\""); out.println(" alt=\"U.S. Health &amp; Human Services\" />"); out.println(" <area shape=\"rect\" coords=\"103,1,147,31\""); out.println(" href=\"http://www.nih.gov/\" target=\"_blank\""); out.println(" alt=\"National Institutes of Health\" />"); out.println(" <area shape=\"rect\" coords=\"148,1,235,33\""); out.println(" href=\"http://www.usa.gov/\" target=\"_blank\""); out.println(" alt=\"USA.gov\" />"); out.println(" </map>"); out.println("</div>"); out.println("<!-- end footer -->"); out.println("</div>"); out.println(""); out.println(""); out.println(" </div> <!-- pagecontent -->"); out.println(" </div> <!-- main-area -->"); out.println(" <div class=\"mainbox-bottom\"><img src=\"/ncitbrowser/images/mainbox-bottom.gif\" width=\"745\" height=\"5\" alt=\"Mainbox Bottom\" /></div>"); out.println(""); out.println(" </div> <!-- center-page -->"); out.println(""); out.println("</body>"); out.println("</html>"); out.println(""); } public static void addQuickLink(HttpServletRequest request, PrintWriter out) { String basePath = request.getContextPath(); String ncim_url = new DataUtils().getNCImURL(); String quicklink_dictionary = (String) request.getSession().getAttribute("dictionary"); quicklink_dictionary = DataUtils.getFormalName(quicklink_dictionary); String term_suggestion_application_url2 = ""; String dictionary_encoded2 = ""; if (quicklink_dictionary != null) { term_suggestion_application_url2 = DataUtils.getMetadataValue(quicklink_dictionary, "term_suggestion_application_url"); dictionary_encoded2 = DataUtils.replaceAll(quicklink_dictionary, " ", "%20"); } out.write(" <div id=\"quicklinksholder\">\r\n"); out.write(" <ul id=\"quicklinks\"\r\n"); out.write(" onmouseover=\"document.quicklinksimg.src='"); out.print(basePath); out.write("/images/quicklinks-active.gif';\"\r\n"); out.write(" onmouseout=\"document.quicklinksimg.src='"); out.print(basePath); out.write("/images/quicklinks-inactive.gif';\">\r\n"); out.write(" <li>\r\n"); out.write(" <a href=\"#\" tabindex=\"-1\"><img src=\""); out.print(basePath); out.write("/images/quicklinks-inactive.gif\" width=\"162\"\r\n"); out.write(" height=\"18\" border=\"0\" name=\"quicklinksimg\" alt=\"Quick Links\" />\r\n"); out.write(" </a>\r\n"); out.write(" <ul>\r\n"); out.write(" <li><a href=\"http://evs.nci.nih.gov/\" tabindex=\"-1\" target=\"_blank\"\r\n"); out.write(" alt=\"Enterprise Vocabulary Services\">EVS Home</a></li>\r\n"); out.write(" <li><a href=\""); out.print(ncim_url); out.write("\" tabindex=\"-1\" target=\"_blank\"\r\n"); out.write(" alt=\"NCI Metathesaurus\">NCI Metathesaurus Browser</a></li>\r\n"); out.write("\r\n"); out.write(" "); if (quicklink_dictionary == null || quicklink_dictionary.compareTo("NCI Thesaurus") != 0) { out.write("\r\n"); out.write("\r\n"); out.write(" <li><a href=\""); out.print( request.getContextPath() ); out.write("/index.jsp\" tabindex=\"-1\"\r\n"); out.write(" alt=\"NCI Thesaurus Browser\">NCI Thesaurus Browser</a></li>\r\n"); out.write("\r\n"); out.write(" "); } out.write("\r\n"); out.write("\r\n"); out.write(" <li>\r\n"); out.write(" <a href=\""); out.print( request.getContextPath() ); out.write("/termbrowser.jsf\" tabindex=\"-1\" alt=\"NCI Term Browser\">NCI Term Browser</a>\r\n"); out.write(" </li>\r\n"); out.write(" \r\n"); out.write(" <li><a href=\"http://www.cancer.gov/cancertopics/terminologyresources\" tabindex=\"-1\" target=\"_blank\"\r\n"); out.write(" alt=\"NCI Terminology Resources\">NCI Terminology Resources</a></li>\r\n"); out.write(" "); if (term_suggestion_application_url2 != null && term_suggestion_application_url2.length() > 0) { out.write("\r\n"); out.write(" <li><a href=\""); out.print(term_suggestion_application_url2); out.write("?dictionary="); out.print(dictionary_encoded2); out.write("\" tabindex=\"-1\" target=\"_blank\" alt=\"Term Suggestion\">Term Suggestion</a></li>\r\n"); out.write(" "); } out.write("\r\n"); out.write("\r\n"); out.write(" </ul>\r\n"); out.write(" </li>\r\n"); out.write(" </ul>\r\n"); out.write(" </div>\r\n"); } }
software/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AjaxServlet.java
package gov.nih.nci.evs.browser.servlet; import org.json.*; import gov.nih.nci.evs.browser.utils.*; import gov.nih.nci.evs.browser.common.*; import java.io.*; import java.util.*; import java.net.URI; import javax.servlet.*; import javax.servlet.http.*; import org.apache.log4j.*; import gov.nih.nci.evs.browser.properties.*; import static gov.nih.nci.evs.browser.common.Constants.*; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag; import org.LexGrid.valueSets.ValueSetDefinition; import org.LexGrid.LexBIG.DataModel.Collections.*; import org.LexGrid.LexBIG.DataModel.Core.*; import org.LexGrid.LexBIG.LexBIGService.*; import org.LexGrid.LexBIG.Utility.*; import org.LexGrid.codingSchemes.*; import org.LexGrid.naming.*; import org.LexGrid.LexBIG.Impl.Extensions.GenericExtensions.*; import org.apache.log4j.*; import javax.faces.event.ValueChangeEvent; import org.LexGrid.LexBIG.caCore.interfaces.LexEVSDistributed; import org.lexgrid.valuesets.LexEVSValueSetDefinitionServices; import org.LexGrid.valueSets.ValueSetDefinition; import org.LexGrid.commonTypes.Source; import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference; import org.lexgrid.valuesets.dto.ResolvedValueSetDefinition; import org.LexGrid.LexBIG.Utility.Iterators.ResolvedConceptReferencesIterator; import javax.servlet.ServletOutputStream; import org.LexGrid.concepts.*; import org.lexgrid.valuesets.dto.ResolvedValueSetCodedNodeSet; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType; import org.LexGrid.concepts.Definition; import org.LexGrid.commonTypes.PropertyQualifier; import org.LexGrid.commonTypes.Property; /** * <!-- LICENSE_TEXT_START --> * Copyright 2008,2009 NGIT. This software was developed in conjunction * with the National Cancer Institute, and so to the extent government * employees are co-authors, any rights in such works shall be subject * to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the disclaimer of Article 3, * below. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * 2. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by NGIT and the National * Cancer Institute." If no such end-user documentation is to be * included, this acknowledgment shall appear in the software itself, * wherever such third-party acknowledgments normally appear. * 3. The names "The National Cancer Institute", "NCI" and "NGIT" must * not be used to endorse or promote products derived from this software. * 4. This license does not authorize the incorporation of this software * into any third party proprietary programs. This license does not * authorize the recipient to use any trademarks owned by either NCI * or NGIT * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED * WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE * DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, * NGIT, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * <!-- LICENSE_TEXT_END --> */ /** * @author EVS Team * @version 1.0 * * Modification history * Initial implementation [email protected] * */ public final class AjaxServlet extends HttpServlet { private static Logger _logger = Logger.getLogger(AjaxServlet.class); /** * local constants */ private static final long serialVersionUID = 1L; //private static final int STANDARD_VIEW = 1; //private static final int TERMINOLOGY_VIEW = 2; /** * Validates the Init and Context parameters, configures authentication URL * * @throws ServletException if the init parameters are invalid or any other * problems occur during initialisation */ public void init() throws ServletException { } /** * Route the user to the execute method * * @param request The HTTP request we are processing * @param response The HTTP response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { execute(request, response); } /** * Route the user to the execute method * * @param request The HTTP request we are processing * @param response The HTTP response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a Servlet exception occurs */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { execute(request, response); } private static void debugJSONString(String msg, String jsonString) { boolean debug = false; //DYEE_DEBUG (default: false) if (! debug) return; _logger.debug(Utils.SEPARATOR); if (msg != null && msg.length() > 0) _logger.debug(msg); _logger.debug("jsonString: " + jsonString); _logger.debug("jsonString length: " + jsonString.length()); Utils.debugJSONString(jsonString); } public static void search_tree(HttpServletResponse response, String node_id, String ontology_display_name, String ontology_version) { try { String jsonString = search_tree(node_id, ontology_display_name, ontology_version); if (jsonString == null) return; JSONObject json = new JSONObject(); JSONArray rootsArray = new JSONArray(jsonString); json.put("root_nodes", rootsArray); response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(json.toString()); response.getWriter().flush(); } catch (Exception e) { e.printStackTrace(); } } public static String search_tree(String node_id, String ontology_display_name, String ontology_version) throws Exception { if (node_id == null || ontology_display_name == null) return null; Utils.StopWatch stopWatch = new Utils.StopWatch(); // String max_tree_level_str = // NCItBrowserProperties.getProperty( // NCItBrowserProperties.MAXIMUM_TREE_LEVEL); // int maxLevel = Integer.parseInt(max_tree_level_str); CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (ontology_version != null) versionOrTag.setVersion(ontology_version); String jsonString = CacheController.getTree( ontology_display_name, versionOrTag, node_id); debugJSONString("Section: search_tree", jsonString); _logger.debug("search_tree: " + stopWatch.getResult()); return jsonString; } /** * Process the specified HTTP request, and create the corresponding HTTP * response (or forward to another web component that will create it). * * @param request The HTTP request we are processing * @param response The HTTP response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs */ public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Determine request by attributes String action = request.getParameter("action");// DataConstants.ACTION); String node_id = request.getParameter("ontology_node_id");// DataConstants.ONTOLOGY_NODE_ID); String ontology_display_name = request.getParameter("ontology_display_name");// DataConstants.ONTOLOGY_DISPLAY_NAME); String ontology_version = request.getParameter("version"); if (ontology_version == null) { ontology_version = DataUtils.getVocabularyVersionByTag(ontology_display_name, "PRODUCTION"); } long ms = System.currentTimeMillis(); if (action.equals("expand_tree")) { if (node_id != null && ontology_display_name != null) { System.out.println("(*) EXPAND TREE NODE: " + node_id); response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; try { /* // for HL7 (temporary fix) ontology_display_name = DataUtils.searchFormalName(ontology_display_name); */ nodesArray = CacheController.getInstance().getSubconcepts( ontology_display_name, ontology_version, node_id); if (nodesArray != null) { json.put("nodes", nodesArray); } } catch (Exception e) { } debugJSONString("Section: expand_tree", json.toString()); response.getWriter().write(json.toString()); /* _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); */ } } /* * else if (action.equals("search_tree")) { * * * if (node_id != null && ontology_display_name != null) { * response.setContentType("text/html"); * response.setHeader("Cache-Control", "no-cache"); JSONObject json = * new JSONObject(); try { // testing // JSONArray rootsArray = // * CacheController.getInstance().getPathsToRoots(ontology_display_name, * // null, node_id, true); * * String max_tree_level_str = null; int maxLevel = -1; try { * max_tree_level_str = NCItBrowserProperties .getInstance() * .getProperty( NCItBrowserProperties.MAXIMUM_TREE_LEVEL); maxLevel = * Integer.parseInt(max_tree_level_str); * * } catch (Exception ex) { * * } * * JSONArray rootsArray = CacheController.getInstance() * .getPathsToRoots(ontology_display_name, null, node_id, true, * maxLevel); * * if (rootsArray.length() == 0) { rootsArray = * CacheController.getInstance() .getRootConcepts(ontology_display_name, * null); * * boolean is_root = isRoot(rootsArray, node_id); if (!is_root) { * //rootsArray = null; json.put("dummy_root_nodes", rootsArray); * response.getWriter().write(json.toString()); * response.getWriter().flush(); * * _logger.debug("Run time (milliseconds): " + * (System.currentTimeMillis() - ms)); return; } } * json.put("root_nodes", rootsArray); } catch (Exception e) { * e.printStackTrace(); } * * response.getWriter().write(json.toString()); * response.getWriter().flush(); * * _logger.debug("Run time (milliseconds): " + * (System.currentTimeMillis() - ms)); return; } } */ if (action.equals("search_value_set")) { search_value_set(request, response); } else if (action.equals("create_src_vs_tree")) { create_src_vs_tree(request, response); } else if (action.equals("create_cs_vs_tree")) { create_cs_vs_tree(request, response); } else if (action.equals("search_hierarchy")) { search_hierarchy(request, response, node_id, ontology_display_name, ontology_version); } else if (action.equals("search_tree")) { search_tree(response, node_id, ontology_display_name, ontology_version); } else if (action.equals("build_tree")) { if (ontology_display_name == null) ontology_display_name = CODING_SCHEME_NAME; response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null;// new JSONArray(); try { nodesArray = CacheController.getInstance().getRootConcepts( ontology_display_name, ontology_version); if (nodesArray != null) { json.put("root_nodes", nodesArray); } } catch (Exception e) { e.printStackTrace(); } debugJSONString("Section: build_tree", json.toString()); response.getWriter().write(json.toString()); // response.getWriter().flush(); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); return; } else if (action.equals("build_vs_tree")) { if (ontology_display_name == null) ontology_display_name = CODING_SCHEME_NAME; response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null;// new JSONArray(); try { //HashMap getRootValueSets(String codingSchemeURN) String codingSchemeVersion = null; nodesArray = CacheController.getInstance().getRootValueSets( ontology_display_name, codingSchemeVersion); if (nodesArray != null) { json.put("root_nodes", nodesArray); } } catch (Exception e) { e.printStackTrace(); } response.getWriter().write(json.toString()); //System.out.println(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); return; } else if (action.equals("expand_vs_tree")) { if (node_id != null && ontology_display_name != null) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; try { nodesArray = CacheController.getInstance().getSubValueSets( ontology_display_name, ontology_version, node_id); if (nodesArray != null) { System.out.println("expand_vs_tree nodesArray != null"); json.put("nodes", nodesArray); } else { System.out.println("expand_vs_tree nodesArray == null???"); } } catch (Exception e) { } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); } } else if (action.equals("expand_entire_vs_tree")) { if (node_id != null && ontology_display_name != null) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; try { nodesArray = CacheController.getInstance().getSourceValueSetTree( ontology_display_name, ontology_version, true); if (nodesArray != null) { System.out.println("expand_entire_vs_tree nodesArray != null"); json.put("root_nodes", nodesArray); } else { System.out.println("expand_entire_vs_tree nodesArray == null???"); } } catch (Exception e) { } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); } } else if (action.equals("expand_entire_cs_vs_tree")) { //if (node_id != null && ontology_display_name != null) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; try { nodesArray = CacheController.getInstance().getCodingSchemeValueSetTree( ontology_display_name, ontology_version, true); if (nodesArray != null) { System.out.println("expand_entire_vs_tree nodesArray != null"); json.put("root_nodes", nodesArray); } else { System.out.println("expand_entire_vs_tree nodesArray == null???"); } } catch (Exception e) { } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); //} } else if (action.equals("build_cs_vs_tree")) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null;// new JSONArray(); try { //HashMap getRootValueSets(String codingSchemeURN) String codingSchemeVersion = null; nodesArray = CacheController.getInstance().getRootValueSets(true); if (nodesArray != null) { json.put("root_nodes", nodesArray); } } catch (Exception e) { e.printStackTrace(); } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); return; } else if (action.equals("expand_cs_vs_tree")) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; String vsd_uri = ValueSetHierarchy.getValueSetURI(node_id); node_id = ValueSetHierarchy.getCodingSchemeName(node_id); //if (node_id != null && ontology_display_name != null) { if (node_id != null) { ValueSetDefinition vsd = ValueSetHierarchy.findValueSetDefinitionByURI(vsd_uri); if (vsd == null) { System.out.println("(****) coding scheme name: " + node_id); try { // nodesArray = CacheController.getInstance().getRootValueSets(node_id, null); //nodesArray = CacheController.getInstance().getRootValueSets(node_id, null); //find roots (by source) if (nodesArray != null) { json.put("nodes", nodesArray); } else { System.out.println("expand_vs_tree nodesArray == null???"); } } catch (Exception e) { } } else { try { nodesArray = CacheController.getInstance().getSubValueSets( node_id, null, vsd_uri); if (nodesArray != null) { json.put("nodes", nodesArray); } } catch (Exception e) { } } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); } } else if (action.equals("build_src_vs_tree")) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null;// new JSONArray(); try { //HashMap getRootValueSets(String codingSchemeURN) String codingSchemeVersion = null; nodesArray = //CacheController.getInstance().getRootValueSets(true, true); CacheController.getInstance().build_src_vs_tree(); if (nodesArray != null) { json.put("root_nodes", nodesArray); } } catch (Exception e) { e.printStackTrace(); } response.getWriter().write(json.toString()); //System.out.println(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); return; } else if (action.equals("expand_src_vs_tree")) { if (node_id != null && ontology_display_name != null) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; nodesArray = CacheController.getInstance().expand_src_vs_tree(node_id); if (nodesArray == null) { System.out.println("(*) CacheController returns nodesArray == null"); } try { if (nodesArray != null) { System.out.println("expand_src_vs_tree nodesArray != null"); json.put("nodes", nodesArray); } else { System.out.println("expand_src_vs_tree nodesArray == null???"); } } catch (Exception e) { e.printStackTrace(); } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); } } } private boolean isRoot(JSONArray rootsArray, String code) { for (int i = 0; i < rootsArray.length(); i++) { String node_id = null; try { JSONObject node = rootsArray.getJSONObject(i); node_id = (String) node.get(CacheController.ONTOLOGY_NODE_ID); if (node_id.compareTo(code) == 0) return true; } catch (Exception e) { e.printStackTrace(); } } return false; } private static boolean _debug = false; // DYEE_DEBUG (default: false) private static StringBuffer _debugBuffer = null; public static void println(PrintWriter out, String text) { if (_debug) { _logger.debug("DBG: " + text); _debugBuffer.append(text + "\n"); } out.println(text); } public static void search_hierarchy(HttpServletRequest request, HttpServletResponse response, String node_id, String ontology_display_name, String ontology_version) { Enumeration parameters = request.getParameterNames(); String param = null; while (parameters.hasMoreElements()) { param = (String) parameters.nextElement(); String paramValue = request.getParameter(param); } response.setContentType("text/html"); PrintWriter out = null; try { out = response.getWriter(); } catch (Exception ex) { ex.printStackTrace(); return; } if (_debug) { _debugBuffer = new StringBuffer(); } String localName = DataUtils.getLocalName(ontology_display_name); String formalName = DataUtils.getFormalName(localName); String term_browser_version = DataUtils.getMetadataValue(formalName, ontology_version, "term_browser_version"); String display_name = DataUtils.getMetadataValue(formalName, ontology_version, "display_name"); println(out, ""); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/yahoo-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/event-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/dom-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/animation-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/container-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/connection-min.js\" ></script>"); //println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/autocomplete-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>"); println(out, ""); println(out, ""); println(out, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"); println(out, "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">"); println(out, " <head>"); println(out, " <title>Vocabulary Hierarchy</title>"); println(out, " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />"); println(out, " <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/fonts.css\" />"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/grids.css\" />"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/code.css\" />"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/tree.css\" />"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/search.js\"></script>"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/dropdown.js\"></script>"); println(out, ""); println(out, " <script language=\"JavaScript\">"); println(out, ""); println(out, " var tree;"); println(out, " var nodeIndex;"); println(out, " var rootDescDiv;"); println(out, " var emptyRootDiv;"); println(out, " var treeStatusDiv;"); println(out, " var nodes = [];"); println(out, " var currOpener;"); println(out, ""); println(out, " function load(url,target) {"); println(out, " if (target != '')"); println(out, " target.window.location.href = url;"); println(out, " else"); println(out, " window.location.href = url;"); println(out, " }"); println(out, ""); println(out, " function init() {"); println(out, ""); println(out, " rootDescDiv = new YAHOO.widget.Module(\"rootDesc\", {visible:false} );"); println(out, " resetRootDesc();"); println(out, ""); println(out, " emptyRootDiv = new YAHOO.widget.Module(\"emptyRoot\", {visible:true} );"); println(out, " resetEmptyRoot();"); println(out, ""); println(out, " treeStatusDiv = new YAHOO.widget.Module(\"treeStatus\", {visible:true} );"); println(out, " resetTreeStatus();"); println(out, ""); println(out, " currOpener = opener;"); println(out, " initTree();"); println(out, " }"); println(out, ""); println(out, " function addTreeNode(rootNode, nodeInfo) {"); println(out, " var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); println(out, " var newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); println(out, " var newNode = new YAHOO.widget.TextNode(newNodeData, rootNode, false);"); println(out, " if (nodeInfo.ontology_node_child_count > 0) {"); println(out, " newNode.setDynamicLoad(loadNodeData);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " function buildTree(ontology_node_id, ontology_display_name) {"); println(out, " var handleBuildTreeSuccess = function(o) {"); println(out, " var respTxt = o.responseText;"); println(out, " var respObj = eval('(' + respTxt + ')');"); println(out, " if ( typeof(respObj) != \"undefined\") {"); println(out, " if ( typeof(respObj.root_nodes) != \"undefined\") {"); println(out, " var root = tree.getRoot();"); println(out, " if (respObj.root_nodes.length == 0) {"); println(out, " showEmptyRoot();"); println(out, " }"); println(out, " else {"); println(out, " for (var i=0; i < respObj.root_nodes.length; i++) {"); println(out, " var nodeInfo = respObj.root_nodes[i];"); println(out, " var expand = false;"); println(out, " addTreeNode(root, nodeInfo, expand);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " tree.draw();"); println(out, " }"); println(out, " }"); println(out, " resetTreeStatus();"); println(out, " }"); println(out, ""); println(out, " var handleBuildTreeFailure = function(o) {"); println(out, " resetTreeStatus();"); println(out, " resetEmptyRoot();"); println(out, " alert('responseFailure: ' + o.statusText);"); println(out, " }"); println(out, ""); println(out, " var buildTreeCallback ="); println(out, " {"); println(out, " success:handleBuildTreeSuccess,"); println(out, " failure:handleBuildTreeFailure"); println(out, " };"); println(out, ""); println(out, " if (ontology_display_name!='') {"); println(out, " resetEmptyRoot();"); println(out, ""); println(out, " showTreeLoadingStatus();"); println(out, " var ontology_source = null;"); println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); println(out, " var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " function resetTree(ontology_node_id, ontology_display_name) {"); println(out, ""); println(out, " var handleResetTreeSuccess = function(o) {"); println(out, " var respTxt = o.responseText;"); println(out, " var respObj = eval('(' + respTxt + ')');"); println(out, " if ( typeof(respObj) != \"undefined\") {"); println(out, " if ( typeof(respObj.root_node) != \"undefined\") {"); println(out, " var root = tree.getRoot();"); println(out, " var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";"); println(out, " var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };"); println(out, " var expand = false;"); println(out, " if (respObj.root_node.ontology_node_child_count > 0) {"); println(out, " expand = true;"); println(out, " }"); println(out, " var ontRoot = new YAHOO.widget.TextNode(rootNodeData, root, expand);"); println(out, ""); println(out, " if ( typeof(respObj.child_nodes) != \"undefined\") {"); println(out, " for (var i=0; i < respObj.child_nodes.length; i++) {"); println(out, " var nodeInfo = respObj.child_nodes[i];"); println(out, " addTreeNode(ontRoot, nodeInfo);"); println(out, " }"); println(out, " }"); println(out, " tree.draw();"); println(out, " setRootDesc(respObj.root_node.ontology_node_name, ontology_display_name);"); println(out, " }"); println(out, " }"); println(out, " resetTreeStatus();"); println(out, " }"); println(out, ""); println(out, " var handleResetTreeFailure = function(o) {"); println(out, " resetTreeStatus();"); println(out, " alert('responseFailure: ' + o.statusText);"); println(out, " }"); println(out, ""); println(out, " var resetTreeCallback ="); println(out, " {"); println(out, " success:handleResetTreeSuccess,"); println(out, " failure:handleResetTreeFailure"); println(out, " };"); println(out, " if (ontology_node_id!= '') {"); println(out, " showTreeLoadingStatus();"); println(out, " var ontology_source = null;"); println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); println(out, " var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " function onClickTreeNode(ontology_node_id) {"); out.println(" if (ontology_node_id.indexOf(\"_dot_\") != -1) return;"); println(out, " var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); println(out, " load('/ncitbrowser/ConceptReport.jsp?dictionary='+ ontology_display_name + '&version='+ ontology_version + '&code=' + ontology_node_id, currOpener);"); println(out, " }"); println(out, ""); println(out, " function onClickViewEntireOntology(ontology_display_name) {"); println(out, " var ontology_display_name = document.pg_form.ontology_display_name.value;"); println(out, " tree = new YAHOO.widget.TreeView(\"treecontainer\");"); println(out, " tree.draw();"); println(out, " resetRootDesc();"); println(out, " buildTree('', ontology_display_name);"); println(out, " }"); println(out, ""); println(out, " function initTree() {"); println(out, ""); println(out, " tree = new YAHOO.widget.TreeView(\"treecontainer\");"); println(out, " var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;"); println(out, " var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); println(out, ""); println(out, " if (ontology_node_id == null || ontology_node_id == \"null\")"); println(out, " {"); println(out, " buildTree(ontology_node_id, ontology_display_name);"); println(out, " }"); println(out, " else"); println(out, " {"); println(out, " searchTree(ontology_node_id, ontology_display_name);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " function initRootDesc() {"); println(out, " rootDescDiv.setBody('');"); println(out, " initRootDesc.show();"); println(out, " rootDescDiv.render();"); println(out, " }"); println(out, ""); println(out, " function resetRootDesc() {"); println(out, " rootDescDiv.hide();"); println(out, " rootDescDiv.setBody('');"); println(out, " rootDescDiv.render();"); println(out, " }"); println(out, ""); println(out, " function resetEmptyRoot() {"); println(out, " emptyRootDiv.hide();"); println(out, " emptyRootDiv.setBody('');"); println(out, " emptyRootDiv.render();"); println(out, " }"); println(out, ""); println(out, " function resetTreeStatus() {"); println(out, " treeStatusDiv.hide();"); println(out, " treeStatusDiv.setBody('');"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showEmptyRoot() {"); println(out, " emptyRootDiv.setBody(\"<span class='instruction_text'>No root nodes available.</span>\");"); println(out, " emptyRootDiv.show();"); println(out, " emptyRootDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showNodeNotFound(node_id) {"); println(out, " //emptyRootDiv.setBody(\"<span class='instruction_text'>Concept with code \" + node_id + \" not found in the hierarchy.</span>\");"); println(out, " emptyRootDiv.setBody(\"<span class='instruction_text'>Concept not part of the parent-child hierarchy in this source; check other relationships.</span>\");"); println(out, " emptyRootDiv.show();"); println(out, " emptyRootDiv.render();"); println(out, " }"); println(out, " "); println(out, " function showPartialHierarchy() {"); println(out, " rootDescDiv.setBody(\"<span class='instruction_text'>(Note: This tree only shows partial hierarchy.)</span>\");"); println(out, " rootDescDiv.show();"); println(out, " rootDescDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showTreeLoadingStatus() {"); println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Building tree ...</span>\");"); println(out, " treeStatusDiv.show();"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showTreeDrawingStatus() {"); println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Drawing tree ...</span>\");"); println(out, " treeStatusDiv.show();"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showSearchingTreeStatus() {"); println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Searching tree... Please wait.</span>\");"); println(out, " treeStatusDiv.show();"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showConstructingTreeStatus() {"); println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Constructing tree... Please wait.</span>\");"); println(out, " treeStatusDiv.show();"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); /* println(out, " function loadNodeData(node, fnLoadComplete) {"); println(out, " var id = node.data.id;"); println(out, ""); println(out, " var responseSuccess = function(o)"); println(out, " {"); println(out, " var path;"); println(out, " var dirs;"); println(out, " var files;"); println(out, " var respTxt = o.responseText;"); println(out, " var respObj = eval('(' + respTxt + ')');"); println(out, " var fileNum = 0;"); println(out, " var categoryNum = 0;"); println(out, " if ( typeof(respObj.nodes) != \"undefined\") {"); println(out, " for (var i=0; i < respObj.nodes.length; i++) {"); println(out, " var name = respObj.nodes[i].ontology_node_name;"); println(out, " var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); println(out, " var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); println(out, " var newNode = new YAHOO.widget.TextNode(newNodeData, node, false);"); println(out, " if (respObj.nodes[i].ontology_node_child_count > 0) {"); println(out, " newNode.setDynamicLoad(loadNodeData);"); println(out, " }"); println(out, " }"); println(out, " }"); println(out, " tree.draw();"); println(out, " fnLoadComplete();"); println(out, " }"); */ out.println(" function loadNodeData(node, fnLoadComplete) {"); out.println(" var id = node.data.id;"); out.println(""); out.println(" var responseSuccess = function(o)"); out.println(" {"); out.println(" var path;"); out.println(" var dirs;"); out.println(" var files;"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" var fileNum = 0;"); out.println(" var categoryNum = 0;"); out.println(" var pos = id.indexOf(\"_dot_\");"); out.println(" if ( typeof(respObj.nodes) != \"undefined\") {"); out.println(" if (pos == -1) {"); out.println(" for (var i=0; i < respObj.nodes.length; i++) {"); out.println(" var name = respObj.nodes[i].ontology_node_name;"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); out.println(" var newNode = new YAHOO.widget.TextNode(newNodeData, node, false);"); out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" } else {"); out.println(""); out.println(" var parent = node.parent;"); out.println(" for (var i=0; i < respObj.nodes.length; i++) {"); out.println(" var name = respObj.nodes[i].ontology_node_name;"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); out.println(""); out.println(" var newNode = new YAHOO.widget.TextNode(newNodeData, parent, true);"); out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" tree.removeNode(node,true);"); out.println(" }"); out.println(" }"); out.println(" fnLoadComplete();"); out.println(" }"); println(out, ""); println(out, " var responseFailure = function(o){"); println(out, " alert('responseFailure: ' + o.statusText);"); println(out, " }"); println(out, ""); println(out, " var callback ="); println(out, " {"); println(out, " success:responseSuccess,"); println(out, " failure:responseFailure"); println(out, " };"); println(out, ""); println(out, " var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); //println(out, " var ontology_display_name = " + "\"" + ontology_display_name + "\";"); //println(out, " var ontology_version = " + "\"" + ontology_version + "\";"); println(out, " var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);"); println(out, " }"); println(out, ""); println(out, " function setRootDesc(rootNodeName, ontology_display_name) {"); println(out, " var newDesc = \"<span class='instruction_text'>Root set to <b>\" + rootNodeName + \"</b></span>\";"); println(out, " rootDescDiv.setBody(newDesc);"); println(out, " var footer = \"<a onClick='javascript:onClickViewEntireOntology();' href='#' class='link_text'>view full ontology}</a>\";"); println(out, " rootDescDiv.setFooter(footer);"); println(out, " rootDescDiv.show();"); println(out, " rootDescDiv.render();"); println(out, " }"); println(out, ""); println(out, ""); println(out, " function searchTree(ontology_node_id, ontology_display_name) {"); println(out, ""); println(out, " var root = tree.getRoot();"); //new ViewInHierarchyUtil().printTree(out, ontology_display_name, ontology_version, node_id); new ViewInHierarchyUtils().printTree(out, ontology_display_name, ontology_version, node_id); println(out, " showPartialHierarchy();"); println(out, " tree.draw();"); println(out, " }"); println(out, ""); println(out, ""); println(out, " function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {"); println(out, " var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); println(out, " var newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); println(out, ""); println(out, " var expand = false;"); println(out, " var childNodes = nodeInfo.children_nodes;"); println(out, ""); println(out, " if (childNodes.length > 0) {"); println(out, " expand = true;"); println(out, " }"); println(out, " var newNode = new YAHOO.widget.TextNode(newNodeData, rootNode, expand);"); println(out, " if (nodeInfo.ontology_node_id == ontology_node_id) {"); println(out, " newNode.labelStyle = \"ygtvlabel_highlight\";"); println(out, " }"); println(out, ""); println(out, " if (nodeInfo.ontology_node_id == ontology_node_id) {"); println(out, " newNode.isLeaf = true;"); println(out, " if (nodeInfo.ontology_node_child_count > 0) {"); println(out, " newNode.isLeaf = false;"); println(out, " newNode.setDynamicLoad(loadNodeData);"); println(out, " } else {"); println(out, " tree.draw();"); println(out, " }"); println(out, ""); println(out, " } else {"); println(out, " if (nodeInfo.ontology_node_id != ontology_node_id) {"); println(out, " if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {"); println(out, " newNode.isLeaf = true;"); println(out, " } else if (childNodes.length == 0) {"); println(out, " newNode.setDynamicLoad(loadNodeData);"); println(out, " }"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " tree.draw();"); println(out, " for (var i=0; i < childNodes.length; i++) {"); println(out, " var childnodeInfo = childNodes[i];"); println(out, " addTreeBranch(ontology_node_id, newNode, childnodeInfo);"); println(out, " }"); println(out, " }"); println(out, " YAHOO.util.Event.addListener(window, \"load\", init);"); println(out, ""); println(out, " </script>"); println(out, "</head>"); println(out, "<body>"); println(out, " "); println(out, " <!-- Begin Skip Top Navigation -->"); println(out, " <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>"); println(out, " <!-- End Skip Top Navigation --> "); println(out, " <div id=\"popupContainer\">"); println(out, " <!-- nci popup banner -->"); println(out, " <div class=\"ncipopupbanner\">"); println(out, " <a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\"><img src=\"/ncitbrowser/images/nci-banner-1.gif\" width=\"440\" height=\"39\" border=\"0\" alt=\"National Cancer Institute\" /></a>"); println(out, " <a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\"><img src=\"/ncitbrowser/images/spacer.gif\" width=\"48\" height=\"39\" border=\"0\" alt=\"National Cancer Institute\" class=\"print-header\" /></a>"); println(out, " </div>"); println(out, " <!-- end nci popup banner -->"); println(out, " <div id=\"popupMainArea\">"); println(out, " <a name=\"evs-content\" id=\"evs-content\"></a>"); println(out, " <table class=\"evsLogoBg\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"); println(out, " <tr>"); println(out, " <td valign=\"top\">"); println(out, " <a href=\"http://evs.nci.nih.gov/\" target=\"_blank\" alt=\"Enterprise Vocabulary Services\">"); println(out, " <img src=\"/ncitbrowser/images/evs-popup-logo.gif\" width=\"213\" height=\"26\" alt=\"EVS: Enterprise Vocabulary Services\" title=\"EVS: Enterprise Vocabulary Services\" border=\"0\" />"); println(out, " </a>"); println(out, " </td>"); println(out, " <td valign=\"top\"><div id=\"closeWindow\"><a href=\"javascript:window.close();\"><img src=\"/ncitbrowser/images/thesaurus_close_icon.gif\" width=\"10\" height=\"10\" border=\"0\" alt=\"Close Window\" />&nbsp;CLOSE WINDOW</a></div></td>"); println(out, " </tr>"); println(out, " </table>"); println(out, ""); println(out, ""); String release_date = DataUtils.getVersionReleaseDate(ontology_display_name, ontology_version); if (ontology_display_name.compareTo("NCI Thesaurus") == 0 || ontology_display_name.compareTo("NCI_Thesaurus") == 0) { println(out, " <div>"); println(out, " <img src=\"/ncitbrowser/images/thesaurus_popup_banner.gif\" width=\"612\" height=\"56\" alt=\"NCI Thesaurus\" title=\"\" border=\"0\" />"); println(out, " "); println(out, " "); println(out, " <span class=\"texttitle-blue-rightjust-2\">" + ontology_version + " (Release date: " + release_date + ")</span>"); println(out, " "); println(out, ""); println(out, " </div>"); } else { println(out, " <div>"); println(out, " <img src=\"/ncitbrowser/images/other_popup_banner.gif\" width=\"612\" height=\"56\" alt=\"" + display_name + "\" title=\"\" border=\"0\" />"); println(out, " <div class=\"vocabularynamepopupshort\">" + display_name ); println(out, " "); println(out, " "); println(out, " <span class=\"texttitle-blue-rightjust\">" + ontology_version + " (Release date: " + release_date + ")</span>"); println(out, " "); println(out, " "); println(out, " </div>"); println(out, " </div>"); } println(out, ""); println(out, " <div id=\"popupContentArea\">"); println(out, " <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">"); println(out, " <tr class=\"textbody\">"); println(out, " <td class=\"pageTitle\" align=\"left\">"); println(out, " " + display_name + " Hierarchy"); println(out, " </td>"); println(out, " <td class=\"pageTitle\" align=\"right\">"); println(out, " <font size=\"1\" color=\"red\" align=\"right\">"); println(out, " <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>"); println(out, " </font>"); println(out, " </td>"); println(out, " </tr>"); println(out, " </table>"); if (! ServerMonitorThread.getInstance().isLexEVSRunning()) { println(out, " <div class=\"textbodyredsmall\">" + ServerMonitorThread.getInstance().getMessage() + "</div>"); } else { println(out, " <!-- Tree content -->"); println(out, " <div id=\"rootDesc\">"); println(out, " <div id=\"bd\"></div>"); println(out, " <div id=\"ft\"></div>"); println(out, " </div>"); println(out, " <div id=\"treeStatus\">"); println(out, " <div id=\"bd\"></div>"); println(out, " </div>"); println(out, " <div id=\"emptyRoot\">"); println(out, " <div id=\"bd\"></div>"); println(out, " </div>"); println(out, " <div id=\"treecontainer\"></div>"); } println(out, ""); println(out, " <form id=\"pg_form\">"); println(out, " "); String ontology_node_id_value = HTTPUtils.cleanXSS(node_id); String ontology_display_name_value = HTTPUtils.cleanXSS(ontology_display_name); String ontology_version_value = HTTPUtils.cleanXSS(ontology_version); println(out, " <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"" + ontology_node_id_value + "\" />"); println(out, " <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"" + ontology_display_name_value + "\" />"); //println(out, " <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"" + scheme_value + "\" />"); println(out, " <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"" + ontology_version_value + "\" />"); println(out, ""); println(out, " </form>"); println(out, " <!-- End of Tree control content -->"); println(out, " </div>"); println(out, " </div>"); println(out, " </div>"); println(out, " "); println(out, "</body>"); println(out, "</html>"); if (_debug) { _logger.debug(Utils.SEPARATOR); _logger.debug("VIH HTML:\n" + _debugBuffer); _debugBuffer = null; _logger.debug(Utils.SEPARATOR); } } public static void create_src_vs_tree(HttpServletRequest request, HttpServletResponse response) { create_vs_tree(request, response, Constants.STANDARD_VIEW); } public static void create_cs_vs_tree(HttpServletRequest request, HttpServletResponse response) { String dictionary = (String) request.getParameter("dictionary"); if (!DataUtils.isNull(dictionary)) { String version = (String) request.getParameter("version"); create_vs_tree(request, response, Constants.TERMINOLOGY_VIEW, dictionary, version); } else { create_vs_tree(request, response, Constants.TERMINOLOGY_VIEW); } } public static void create_vs_tree(HttpServletRequest request, HttpServletResponse response, int view) { response.setContentType("text/html"); PrintWriter out = null; try { out = response.getWriter(); } catch (Exception ex) { ex.printStackTrace(); return; } String message = (String) request.getSession().getAttribute("message"); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"); out.println("<html xmlns:c=\"http://java.sun.com/jsp/jstl/core\">"); out.println("<head>"); if (view == Constants.STANDARD_VIEW) { out.println(" <title>NCI Term Browser - Value Set Source View</title>"); } else { out.println(" <title>NCI Term Browser - Value Set Terminology View</title>"); } //out.println(" <title>NCI Thesaurus</title>"); out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"); out.println(""); out.println("<style type=\"text/css\">"); out.println("/*margin and padding on body element"); out.println(" can introduce errors in determining"); out.println(" element position and are not recommended;"); out.println(" we turn them off as a foundation for YUI"); out.println(" CSS treatments. */"); out.println("body {"); out.println(" margin:0;"); out.println(" padding:0;"); out.println("}"); out.println("</style>"); out.println(""); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/fonts/fonts-min.css\" />"); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/treeview/assets/skins/sam/treeview.css\" />"); out.println(""); out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js\"></script>"); //Before(GF31982): out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/treeview/treeview-min.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>"); //GF31982 out.println(""); out.println(""); out.println("<!-- Dependency -->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js\"></script>"); out.println(""); out.println("<!-- Source file -->"); out.println("<!--"); out.println(" If you require only basic HTTP transaction support, use the"); out.println(" connection_core.js file."); out.println("-->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js\"></script>"); out.println(""); out.println("<!--"); out.println(" Use the full connection.js if you require the following features:"); out.println(" - Form serialization."); out.println(" - File Upload using the iframe transport."); out.println(" - Cross-domain(XDR) transactions."); out.println("-->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js\"></script>"); out.println(""); out.println(""); out.println(""); out.println("<!--begin custom header content for this example-->"); out.println("<!--Additional custom style rules for this example:-->"); out.println("<style type=\"text/css\">"); out.println(""); out.println(""); out.println(".ygtvcheck0 { background: url(/ncitbrowser/images/yui/treeview/check0.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(".ygtvcheck1 { background: url(/ncitbrowser/images/yui/treeview/check1.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(".ygtvcheck2 { background: url(/ncitbrowser/images/yui/treeview/check2.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(""); out.println(""); out.println(".ygtv-edit-TaskNode { width: 190px;}"); out.println(".ygtv-edit-TaskNode .ygtvcancel, .ygtv-edit-TextNode .ygtvok { border:none;}"); out.println(".ygtv-edit-TaskNode .ygtv-button-container { float: right;}"); out.println(".ygtv-edit-TaskNode .ygtv-input input{ width: 140px;}"); out.println(".whitebg {"); out.println(" background-color:white;"); out.println("}"); out.println("</style>"); out.println(""); out.println(" <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />"); out.println(" <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />"); out.println(""); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tasknode.js\"></script>"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/search.js\"></script>"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/dropdown.js\"></script>"); out.println(""); out.println(" <script type=\"text/javascript\">"); out.println(""); out.println(" function refresh() {"); out.println(""); out.println(" var selectValueSetSearchOptionObj = document.forms[\"valueSetSearchForm\"].selectValueSetSearchOption;"); out.println(""); out.println(" for (var i=0; i<selectValueSetSearchOptionObj.length; i++) {"); out.println(" if (selectValueSetSearchOptionObj[i].checked) {"); out.println(" selectValueSetSearchOption = selectValueSetSearchOptionObj[i].value;"); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(" window.location.href=\"/ncitbrowser/pages/value_set_source_view.jsf?refresh=1\""); //Before(GF31982) //GF31982(Not Sure): out.println(" window.location.href=\"/ncitbrowser/ajax?action=create_src_vs_tree?refresh=1\""); out.println(" + \"&nav_type=valuesets\" + \"&opt=\"+ selectValueSetSearchOption;"); out.println(""); out.println(" }"); out.println(" </script>"); out.println(""); out.println(" <script language=\"JavaScript\">"); out.println(""); out.println(" var tree;"); out.println(" var nodeIndex;"); out.println(" var nodes = [];"); out.println(""); out.println(" function load(url,target) {"); out.println(" if (target != '')"); out.println(" target.window.location.href = url;"); out.println(" else"); out.println(" window.location.href = url;"); out.println(" }"); out.println(""); out.println(" function init() {"); out.println(" //initTree();"); out.println(" }"); out.println(""); out.println(" //handler for expanding all nodes"); out.println(" YAHOO.util.Event.on(\"expand_all\", \"click\", function(e) {"); out.println(" //expandEntireTree();"); out.println(""); out.println(" tree.expandAll();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for collapsing all nodes"); out.println(" YAHOO.util.Event.on(\"collapse_all\", \"click\", function(e) {"); out.println(" tree.collapseAll();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for checking all nodes"); out.println(" YAHOO.util.Event.on(\"check_all\", \"click\", function(e) {"); out.println(" check_all();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for unchecking all nodes"); out.println(" YAHOO.util.Event.on(\"uncheck_all\", \"click\", function(e) {"); out.println(" uncheck_all();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(""); out.println(""); out.println(" YAHOO.util.Event.on(\"getchecked\", \"click\", function(e) {"); out.println(" //alert(\"Checked nodes: \" + YAHOO.lang.dump(getCheckedNodes()), \"info\", \"example\");"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(""); out.println(" });"); out.println(""); out.println(""); out.println(" function addTreeNode(rootNode, nodeInfo) {"); out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); out.println(""); out.println(" if (nodeInfo.ontology_node_id.indexOf(\"TVS_\") >= 0) {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };"); out.println(" } else {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); out.println(" }"); out.println(""); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, false);"); out.println(" if (nodeInfo.ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function buildTree(ontology_node_id, ontology_display_name) {"); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" }"); out.println(" else {"); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" var expand = false;"); out.println(" //addTreeNode(root, nodeInfo, expand);"); out.println(""); out.println(" addTreeNode(root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" tree.draw();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_src_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function resetTree(ontology_node_id, ontology_display_name) {"); out.println(""); out.println(" var handleResetTreeSuccess = function(o) {"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(" if ( typeof(respObj.root_node) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";"); out.println(" var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };"); out.println(" var expand = false;"); out.println(" if (respObj.root_node.ontology_node_child_count > 0) {"); out.println(" expand = true;"); out.println(" }"); out.println(" var ontRoot = new YAHOO.widget.TaskNode(rootNodeData, root, expand);"); out.println(""); out.println(" if ( typeof(respObj.child_nodes) != \"undefined\") {"); out.println(" for (var i=0; i < respObj.child_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.child_nodes[i];"); out.println(" addTreeNode(ontRoot, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" tree.draw();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleResetTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var resetTreeCallback ="); out.println(" {"); out.println(" success:handleResetTreeSuccess,"); out.println(" failure:handleResetTreeFailure"); out.println(" };"); out.println(" if (ontology_node_id!= '') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function onClickTreeNode(ontology_node_id) {"); out.println(" //alert(\"onClickTreeNode \" + ontology_node_id);"); out.println(" window.location = '/ncitbrowser/pages/value_set_treenode_redirect.jsf?ontology_node_id=' + ontology_node_id;"); out.println(" }"); out.println(""); out.println(""); out.println(" function onClickViewEntireOntology(ontology_display_name) {"); out.println(" var ontology_display_name = document.pg_form.ontology_display_name.value;"); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" tree.draw();"); // out.println(" buildTree('', ontology_display_name);"); out.println(" }"); out.println(""); out.println(" function initTree() {"); out.println(""); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" tree.setNodesProperty('propagateHighlightUp',true);"); out.println(" tree.setNodesProperty('propagateHighlightDown',true);"); out.println(" tree.subscribe('keydown',tree._onKeyDownEvent);"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" tree.subscribe(\"expand\", function(node) {"); out.println(""); out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 39 });"); out.println(""); out.println(" });"); out.println(""); out.println(""); out.println(""); out.println(" tree.subscribe(\"collapse\", function(node) {"); out.println(" //alert(\"Collapsing \" + node.label );"); out.println(""); out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 109 });"); out.println(" });"); out.println(""); out.println(" // By default, trees with TextNodes will fire an event for when the label is clicked:"); out.println(" tree.subscribe(\"checkClick\", function(node) {"); out.println(" //alert(node.data.myNodeId + \" label was checked\");"); out.println(" });"); out.println(""); out.println(""); println(out, " var root = tree.getRoot();"); HashMap value_set_tree_hmap = null; if (view == Constants.STANDARD_VIEW) { value_set_tree_hmap = DataUtils.getSourceValueSetTree(); } else { value_set_tree_hmap = DataUtils.getCodingSchemeValueSetTree(); } TreeItem root = (TreeItem) value_set_tree_hmap.get("<Root>"); //new ValueSetUtils().printTree(out, root); new ValueSetUtils().printTree(out, root, view); String contextPath = request.getContextPath(); String view_str = new Integer(view).toString(); //[#31914] Search option and algorithm in value set search box are not preserved in session. //String option = (String) request.getSession().getAttribute("selectValueSetSearchOption"); //String algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm"); String option = (String) request.getParameter("selectValueSetSearchOption"); String algorithm = (String) request.getParameter("valueset_search_algorithm"); String matchText = (String) request.getParameter("matchText"); if (DataUtils.isNull(matchText)) { matchText = (String) request.getSession().getAttribute("matchText"); } if (DataUtils.isNull(matchText)) { matchText = ""; } else { matchText = matchText.trim(); } request.getSession().setAttribute("matchText", matchText); String option_code = ""; String option_name = ""; if (DataUtils.isNull(option)) { option_code = "checked"; } else { if (option.compareToIgnoreCase("Code") == 0) { option_code = "checked"; } if (option.compareToIgnoreCase("Name") == 0) { option_name = "checked"; } } String algorithm_exactMatch = ""; String algorithm_startsWith = ""; String algorithm_contains = ""; if (DataUtils.isNull(algorithm)) { algorithm_exactMatch = "checked"; } else { if (algorithm.compareToIgnoreCase("exactMatch") == 0) { algorithm_exactMatch = "checked"; } if (algorithm.compareToIgnoreCase("startsWith") == 0) { algorithm_startsWith = "checked"; } if (algorithm.compareToIgnoreCase("contains") == 0) { algorithm_contains = "checked"; } } System.out.println("*** OPTION: " + option); System.out.println("*** ALGORITHM: " + algorithm); System.out.println("*** matchText: " + matchText); System.out.println("AjaxServlet option_code: " + option_code); System.out.println("AjaxServlet option_name: " + option_name); System.out.println("AjaxServlet algorithm_exactMatch: " + algorithm_exactMatch); System.out.println("AjaxServlet algorithm_startsWith: " + algorithm_startsWith); System.out.println("AjaxServlet algorithm_contains: " + algorithm_contains); out.println(""); if (message == null) { out.println(" tree.collapseAll();"); } out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(""); out.println(" function onCheckClick(node) {"); out.println(" YAHOO.log(node.label + \" check was clicked, new state: \" + node.checkState, \"info\", \"example\");"); out.println(" }"); out.println(""); out.println(" function check_all() {"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" topNodes[i].check();"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function uncheck_all() {"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" topNodes[i].uncheck();"); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(" function expand_all() {"); out.println(" //alert(\"expand_all\");"); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" onClickViewEntireOntology(ontology_display_name);"); out.println(" }"); out.println(""); out.println(""); // 0=unchecked, 1=some children checked, 2=all children checked out.println(" // Gets the labels of all of the fully checked nodes"); out.println(" // Could be updated to only return checked leaf nodes by evaluating"); out.println(" // the children collection first."); out.println(" function getCheckedNodes(nodes) {"); out.println(" nodes = nodes || tree.getRoot().children;"); out.println(" checkedNodes = [];"); out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {"); out.println(" var n = nodes[i];"); out.println(" if (n.checkState > 0) { // if we were interested in the nodes that have some but not all children checked"); out.println(" //if (n.checkState == 2) {"); out.println(" checkedNodes.push(n.label); // just using label for simplicity"); out.println(""); out.println(" if (n.hasChildren()) {"); out.println(" checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));"); out.println(" }"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(" var checked_vocabularies = document.forms[\"valueSetSearchForm\"].checked_vocabularies;"); out.println(" checked_vocabularies.value = checkedNodes;"); out.println(""); out.println(" return checkedNodes;"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" function loadNodeData(node, fnLoadComplete) {"); out.println(" var id = node.data.id;"); out.println(""); out.println(" var responseSuccess = function(o)"); out.println(" {"); out.println(" var path;"); out.println(" var dirs;"); out.println(" var files;"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" var fileNum = 0;"); out.println(" var categoryNum = 0;"); out.println(" if ( typeof(respObj.nodes) != \"undefined\") {"); out.println(" for (var i=0; i < respObj.nodes.length; i++) {"); out.println(" var name = respObj.nodes[i].ontology_node_name;"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, node, false);"); out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" tree.draw();"); out.println(" fnLoadComplete();"); out.println(" }"); out.println(""); out.println(" var responseFailure = function(o){"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var callback ="); out.println(" {"); out.println(" success:responseSuccess,"); out.println(" failure:responseFailure"); out.println(" };"); out.println(""); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_src_vs_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);"); out.println(" }"); out.println(""); out.println(""); out.println(" function searchTree(ontology_node_id, ontology_display_name) {"); out.println(""); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(""); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(""); out.println(" if ( typeof(respObj.dummy_root_nodes) != \"undefined\") {"); out.println(" showNodeNotFound(ontology_node_id);"); out.println(" }"); out.println(""); out.println(" else if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" }"); out.println(" else {"); out.println(" showPartialHierarchy();"); out.println(" showConstructingTreeStatus();"); out.println(""); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" //var expand = false;"); out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;//document.pg_form.ontology_source.value;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=search_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(" function expandEntireTree() {"); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" //tree.draw();"); out.println(""); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;"); out.println(""); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(""); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(""); out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(""); out.println(" //alert(respObj.root_nodes.length);"); out.println(""); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" } else {"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" //alert(\"calling addTreeBranch \");"); out.println(""); out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_entire_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {"); out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); out.println(""); out.println(" var newNodeData;"); out.println(" if (ontology_node_id.indexOf(\"TVS_\") >= 0) {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };"); out.println(" } else {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); out.println(" }"); out.println(""); out.println(" var expand = false;"); out.println(" var childNodes = nodeInfo.children_nodes;"); out.println(""); out.println(" if (childNodes.length > 0) {"); out.println(" expand = true;"); out.println(" }"); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, expand);"); out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {"); out.println(" newNode.labelStyle = \"ygtvlabel_highlight\";"); out.println(" }"); out.println(""); out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {"); out.println(" newNode.isLeaf = true;"); out.println(" if (nodeInfo.ontology_node_child_count > 0) {"); out.println(" newNode.isLeaf = false;"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" } else {"); out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(" } else {"); out.println(" if (nodeInfo.ontology_node_id != ontology_node_id) {"); out.println(" if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {"); out.println(" newNode.isLeaf = true;"); out.println(" } else if (childNodes.length == 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" tree.draw();"); out.println(" for (var i=0; i < childNodes.length; i++) {"); out.println(" var childnodeInfo = childNodes[i];"); out.println(" addTreeBranch(ontology_node_id, newNode, childnodeInfo);"); out.println(" }"); out.println(" }"); out.println(" YAHOO.util.Event.addListener(window, \"load\", init);"); out.println(""); out.println(" YAHOO.util.Event.onDOMReady(initTree);"); out.println(""); out.println(""); out.println(" </script>"); out.println(""); out.println("</head>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println("<body onLoad=\"document.forms.valueSetSearchForm.matchText.focus();\">"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/wz_tooltip.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_centerwindow.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_followscroll.js\"></script>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" <!-- Begin Skip Top Navigation -->"); out.println(" <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>"); out.println(" <!-- End Skip Top Navigation -->"); out.println(""); out.println("<!-- nci banner -->"); out.println("<div class=\"ncibanner\">"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/logotype.gif\""); out.println(" width=\"440\" height=\"39\" border=\"0\""); out.println(" alt=\"National Cancer Institute\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/spacer.gif\""); out.println(" width=\"48\" height=\"39\" border=\"0\""); out.println(" alt=\"National Cancer Institute\" class=\"print-header\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.nih.gov\" target=\"_blank\" >"); out.println(" <img src=\"/ncitbrowser/images/tagline_nologo.gif\""); out.println(" width=\"173\" height=\"39\" border=\"0\""); out.println(" alt=\"U.S. National Institutes of Health\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/cancer-gov.gif\""); out.println(" width=\"99\" height=\"39\" border=\"0\""); out.println(" alt=\"www.cancer.gov\"/>"); out.println(" </a>"); out.println("</div>"); out.println("<!-- end nci banner -->"); out.println(""); out.println(" <div class=\"center-page\">"); out.println(" <!-- EVS Logo -->"); out.println("<div>"); out.println(" <img src=\"/ncitbrowser/images/evs-logo-swapped.gif\" alt=\"EVS Logo\""); out.println(" width=\"745\" height=\"26\" border=\"0\""); out.println(" usemap=\"#external-evs\" />"); out.println(" <map id=\"external-evs\" name=\"external-evs\">"); out.println(" <area shape=\"rect\" coords=\"0,0,140,26\""); out.println(" href=\"/ncitbrowser/start.jsf\" target=\"_self\""); out.println(" alt=\"NCI Term Browser\" />"); out.println(" <area shape=\"rect\" coords=\"520,0,745,26\""); out.println(" href=\"http://evs.nci.nih.gov/\" target=\"_blank\""); out.println(" alt=\"Enterprise Vocabulary Services\" />"); out.println(" </map>"); out.println("</div>"); out.println(""); out.println(""); out.println("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"); out.println(" <tr>"); out.println(" <td width=\"5\"></td>"); out.println(" <td><a href=\"/ncitbrowser/pages/multiple_search.jsf?nav_type=terminologies\">"); out.println(" <img name=\"tab_terms\" src=\"/ncitbrowser/images/tab_terms.gif\""); out.println(" border=\"0\" alt=\"Terminologies\" title=\"Terminologies\" /></a></td>"); //Before(GF31982): out.println(" <td><a href=\"/ncitbrowser/pages/value_set_source_view.jsf?nav_type=valuesets\">"); out.println(" <td><a href=\"/ncitbrowser/ajax?action=create_src_vs_tree\">"); //GF31982 out.println(" <img name=\"tab_valuesets\" src=\"/ncitbrowser/images/tab_valuesets_clicked.gif\""); out.println(" border=\"0\" alt=\"Value Sets\" title=\"ValueSets\" /></a></td>"); out.println(" <td><a href=\"/ncitbrowser/pages/mapping_search.jsf?nav_type=mappings\">"); out.println(" <img name=\"tab_map\" src=\"/ncitbrowser/images/tab_map.gif\""); out.println(" border=\"0\" alt=\"Mappings\" title=\"Mappings\" /></a></td>"); out.println(" </tr>"); out.println("</table>"); out.println(""); out.println("<div class=\"mainbox-top\"><img src=\"/ncitbrowser/images/mainbox-top.gif\" width=\"745\" height=\"5\" alt=\"\"/></div>"); out.println("<!-- end EVS Logo -->"); out.println(" <!-- Main box -->"); out.println(" <div id=\"main-area\">"); out.println(""); out.println(" <!-- Thesaurus, banner search area -->"); out.println(" <div class=\"bannerarea\">"); out.println(" <a href=\"/ncitbrowser/start.jsf\" style=\"text-decoration: none;\">"); out.println(" <div class=\"vocabularynamebanner_tb\">"); out.println(" <span class=\"vocabularynamelong_tb\">" + JSPUtils.getApplicationVersionDisplay() + "</span>"); out.println(" </div>"); out.println(" </a>"); out.println(" <div class=\"search-globalnav\">"); out.println(" <!-- Search box -->"); out.println(" <div class=\"searchbox-top\"><img src=\"/ncitbrowser/images/searchbox-top.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Top\" /></div>"); out.println(" <div class=\"searchbox\">"); out.println(""); out.println(""); //out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + + "/ajax?action=saerch_value_set_tree\"> "/pages/value_set_source_view.jsf\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">"); out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + "/ajax?action=search_value_set\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">"); out.println("<input type=\"hidden\" name=\"valueSetSearchForm\" value=\"valueSetSearchForm\" />"); out.println("<input type=\"hidden\" name=\"view\" value=\"" + view_str + "\" />"); out.println(""); out.println(""); out.println(""); out.println(" <input type=\"hidden\" id=\"checked_vocabularies\" name=\"checked_vocabularies\" value=\"\" />"); out.println(""); out.println(""); out.println(""); out.println("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 2px\" >"); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(""); out.println(" <input CLASS=\"searchbox-input-2\""); out.println(" name=\"matchText\""); out.println(" value=\"" + matchText + "\""); out.println(" onFocus=\"active = true\""); out.println(" onBlur=\"active = false\""); out.println(" onkeypress=\"return submitEnter('valueSetSearchForm:valueset_search',event)\""); out.println(" tabindex=\"1\"/>"); out.println(""); out.println(""); out.println(" <input id=\"valueSetSearchForm:valueset_search\" type=\"image\" src=\"/ncitbrowser/images/search.gif\" name=\"valueSetSearchForm:valueset_search\" alt=\"Search Value Sets\" onclick=\"javascript:getCheckedNodes();\" tabindex=\"2\" class=\"searchbox-btn\" /><a href=\"/ncitbrowser/pages/help.jsf#searchhelp\" tabindex=\"3\"><img src=\"/ncitbrowser/images/search-help.gif\" alt=\"Search Help\" style=\"border-width:0;\" class=\"searchbox-btn\" /></a>"); out.println(""); out.println(""); out.println(" </td>"); out.println(" </tr>"); out.println(""); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td>"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 0px\">"); out.println(""); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"exactMatch\" alt=\"Exact Match\" " + algorithm_exactMatch + " tabindex=\"3\">Exact Match&nbsp;"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"startsWith\" alt=\"Begins With\" " + algorithm_startsWith + " tabindex=\"3\">Begins With&nbsp;"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"contains\" alt=\"Contains\" " + algorithm_contains + " tabindex=\"3\">Contains"); out.println(" </td>"); out.println(" </tr>"); out.println(""); out.println(" <tr align=\"left\">"); out.println(" <td height=\"1px\" bgcolor=\"#2F2F5F\" align=\"left\"></td>"); out.println(" </tr>"); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Code\" " + option_code + " alt=\"Code\" tabindex=\"1\" >Code&nbsp;"); out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Name\" " + option_name + " alt=\"Name\" tabindex=\"1\" >Name"); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(" </td>"); out.println(" </tr>"); out.println("</table>"); out.println(" <input type=\"hidden\" name=\"referer\" id=\"referer\" value=\"http%3A%2F%2Flocalhost%3A8080%2Fncitbrowser%2Fpages%2Fresolved_value_set_search_results.jsf\">"); out.println(" <input type=\"hidden\" id=\"nav_type\" name=\"nav_type\" value=\"valuesets\" />"); out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />"); out.println(""); out.println("<input type=\"hidden\" name=\"javax.faces.ViewState\" id=\"javax.faces.ViewState\" value=\"j_id22:j_id23\" />"); out.println("</form>"); out.println(" </div> <!-- searchbox -->"); out.println(""); out.println(" <div class=\"searchbox-bottom\"><img src=\"/ncitbrowser/images/searchbox-bottom.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Bottom\" /></div>"); out.println(" <!-- end Search box -->"); out.println(" <!-- Global Navigation -->"); out.println(""); out.println("<table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">"); out.println(" <tr>"); out.println(" <td align=\"left\" valign=\"bottom\">"); out.println(" <a href=\"#\" onclick=\"javascript:window.open('/ncitbrowser/pages/source_help_info-termbrowser.jsf',"); out.println(" '_blank','top=100, left=100, height=740, width=780, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"13\">"); out.println(" Sources</a>"); out.println(""); //KLO, 022612 out.println(" \r\n"); out.println(" "); out.print( VisitedConceptUtils.getDisplayLink(request, true) ); out.println(" \r\n"); // Visited concepts -- to be implemented. // out.println(" | <A href=\"#\" onmouseover=\"Tip('<ul><li><a href=\'/ncitbrowser/ConceptReport.jsp?dictionary=NCI Thesaurus&version=11.09d&code=C44256\'>Ratio &#40;NCI Thesaurus 11.09d&#41;</a><br></li></ul>',WIDTH, 300, TITLE, 'Visited Concepts', SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, CLOSEBTN, true, CLICKCLOSE, true)\" onmouseout=UnTip() >Visited Concepts</A>"); out.println(" </td>"); out.println(" <td align=\"right\" valign=\"bottom\">"); out.println(" <a href=\""); out.print( request.getContextPath() ); out.println("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n"); out.println(" </td>\r\n"); out.println(" <td width=\"7\"></td>\r\n"); out.println(" </tr>\r\n"); out.println("</table>"); /* out.println(" <a href=\"/ncitbrowser/pages/help.jsf\" tabindex=\"16\">Help</a>"); out.println(" </td>"); out.println(" <td width=\"7\"></td>"); out.println(" </tr>"); out.println("</table>"); */ out.println(" <!-- end Global Navigation -->"); out.println(""); out.println(" </div> <!-- search-globalnav -->"); out.println(" </div> <!-- bannerarea -->"); out.println(""); out.println(" <!-- end Thesaurus, banner search area -->"); out.println(" <!-- Quick links bar -->"); out.println(""); out.println("<div class=\"bluebar\">"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); out.println(" <tr>"); out.println(" <td><div class=\"quicklink-status\">&nbsp;</div></td>"); out.println(" <td>"); out.println(""); /* out.println(" <div id=\"quicklinksholder\">"); out.println(" <ul id=\"quicklinks\""); out.println(" onmouseover=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-active.gif';\""); out.println(" onmouseout=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-inactive.gif';\">"); out.println(" <li>"); out.println(" <a href=\"#\" tabindex=\"-1\"><img src=\"/ncitbrowser/images/quicklinks-inactive.gif\" width=\"162\""); out.println(" height=\"18\" border=\"0\" name=\"quicklinksimg\" alt=\"Quick Links\" />"); out.println(" </a>"); out.println(" <ul>"); out.println(" <li><a href=\"http://evs.nci.nih.gov/\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"Enterprise Vocabulary Services\">EVS Home</a></li>"); out.println(" <li><a href=\"http://localhost/ncimbrowserncimbrowser\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"NCI Metathesaurus\">NCI Metathesaurus Browser</a></li>"); out.println(""); out.println(" <li><a href=\"/ncitbrowser/start.jsf\" tabindex=\"-1\""); out.println(" alt=\"NCI Term Browser\">NCI Term Browser</a></li>"); out.println(" <li><a href=\"http://www.cancer.gov/cancertopics/terminologyresources\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"NCI Terminology Resources\">NCI Terminology Resources</a></li>"); out.println(""); out.println(" <li><a href=\"http://ncitermform.nci.nih.gov/ncitermform/?dictionary=NCI%20Thesaurus\" tabindex=\"-1\" target=\"_blank\" alt=\"Term Suggestion\">Term Suggestion</a></li>"); out.println(""); out.println(""); out.println(" </ul>"); out.println(" </li>"); out.println(" </ul>"); out.println(" </div>"); */ addQuickLink(request, out); out.println(""); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(""); out.println("</div>"); if (! ServerMonitorThread.getInstance().isLexEVSRunning()) { out.println(" <div class=\"redbar\">"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); out.println(" <tr>"); out.println(" <td class=\"lexevs-status\">"); out.println(" " + ServerMonitorThread.getInstance().getMessage()); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(" </div>"); } out.println(" <!-- end Quick links bar -->"); out.println(""); out.println(" <!-- Page content -->"); out.println(" <div class=\"pagecontent\">"); out.println(""); if (message != null) { out.println("\r\n"); out.println(" <p class=\"textbodyred\">"); out.print(message); out.println("</p>\r\n"); out.println(" "); request.getSession().removeAttribute("message"); } out.println("<p class=\"textbody\">"); out.println("View value sets organized by standards category or source terminology."); out.println("Standards categories group the value sets supporting them; all other labels lead to the home pages of actual value sets or source terminologies."); out.println("Search or browse a value set from its home page, or search all value sets at once from this page (very slow) to find which ones contain a particular code or term."); out.println("</p>"); out.println(""); out.println(" <div id=\"popupContentArea\">"); out.println(" <a name=\"evs-content\" id=\"evs-content\"></a>"); out.println(""); out.println(" <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" <tr class=\"textbody\">"); out.println(" <td class=\"textbody\" align=\"left\">"); out.println(""); if (view == Constants.STANDARD_VIEW) { out.println(" Standards View"); out.println(" &nbsp;|"); out.println(" <a href=\"" + contextPath + "/ajax?action=create_cs_vs_tree\">Terminology View</a>"); } else { out.println(" <a href=\"" + contextPath + "/ajax?action=create_src_vs_tree\">Standards View</a>"); out.println(" &nbsp;|"); out.println(" Terminology View"); } out.println(" </td>"); out.println(""); out.println(" <td align=\"right\">"); out.println(" <font size=\"1\" color=\"red\" align=\"right\">"); out.println(" <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>"); out.println(" </font>"); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(""); out.println(" <hr/>"); out.println(""); out.println(""); out.println(""); out.println("<style>"); out.println("#expandcontractdiv {border:1px solid #336600; background-color:#FFFFCC; margin:0 0 .5em 0; padding:0.2em;}"); out.println("#treecontainer { background: #fff }"); out.println("</style>"); out.println(""); out.println(""); out.println("<div id=\"expandcontractdiv\">"); out.println(" <a id=\"expand_all\" href=\"#\">Expand all</a>"); out.println(" <a id=\"collapse_all\" href=\"#\">Collapse all</a>"); out.println(" <a id=\"check_all\" href=\"#\">Check all</a>"); out.println(" <a id=\"uncheck_all\" href=\"#\">Uncheck all</a>"); out.println("</div>"); out.println(""); out.println(""); out.println(""); out.println(" <!-- Tree content -->"); out.println(""); out.println(" <div id=\"treecontainer\" class=\"ygtv-checkbox\"></div>"); out.println(""); out.println(" <form id=\"pg_form\">"); out.println(""); out.println(" <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"null\" />"); //out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"null\" />"); //out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />"); out.println(" </form>"); out.println(""); out.println(""); out.println(" </div> <!-- popupContentArea -->"); out.println(""); out.println(""); out.println("<div class=\"textbody\">"); out.println("<!-- footer -->"); out.println("<div class=\"footer\" style=\"width:720px\">"); out.println(" <ul>"); out.println(" <li><a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\">NCI Home</a> |</li>"); out.println(" <li><a href=\"/ncitbrowser/pages/contact_us.jsf\">Contact Us</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies\" target=\"_blank\" alt=\"National Cancer Institute Policies\">Policies</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies/page3\" target=\"_blank\" alt=\"National Cancer Institute Accessibility\">Accessibility</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies/page6\" target=\"_blank\" alt=\"National Cancer Institute FOIA\">FOIA</a></li>"); out.println(" </ul>"); out.println(" <p>"); out.println(" A Service of the National Cancer Institute<br />"); out.println(" <img src=\"/ncitbrowser/images/external-footer-logos.gif\""); out.println(" alt=\"External Footer Logos\" width=\"238\" height=\"34\" border=\"0\""); out.println(" usemap=\"#external-footer\" />"); out.println(" </p>"); out.println(" <map id=\"external-footer\" name=\"external-footer\">"); out.println(" <area shape=\"rect\" coords=\"0,0,46,34\""); out.println(" href=\"http://www.cancer.gov\" target=\"_blank\""); out.println(" alt=\"National Cancer Institute\" />"); out.println(" <area shape=\"rect\" coords=\"55,1,99,32\""); out.println(" href=\"http://www.hhs.gov/\" target=\"_blank\""); out.println(" alt=\"U.S. Health &amp; Human Services\" />"); out.println(" <area shape=\"rect\" coords=\"103,1,147,31\""); out.println(" href=\"http://www.nih.gov/\" target=\"_blank\""); out.println(" alt=\"National Institutes of Health\" />"); out.println(" <area shape=\"rect\" coords=\"148,1,235,33\""); out.println(" href=\"http://www.usa.gov/\" target=\"_blank\""); out.println(" alt=\"USA.gov\" />"); out.println(" </map>"); out.println("</div>"); out.println("<!-- end footer -->"); out.println("</div>"); out.println(""); out.println(""); out.println(" </div> <!-- pagecontent -->"); out.println(" </div> <!-- main-area -->"); out.println(" <div class=\"mainbox-bottom\"><img src=\"/ncitbrowser/images/mainbox-bottom.gif\" width=\"745\" height=\"5\" alt=\"Mainbox Bottom\" /></div>"); out.println(""); out.println(" </div> <!-- center-page -->"); out.println(""); out.println("</body>"); out.println("</html>"); out.println(""); } public static void search_value_set(HttpServletRequest request, HttpServletResponse response) { System.out.println("(*** AjaxServlet ***) search_value_set ..."); String selectValueSetSearchOption = (String) request.getParameter("selectValueSetSearchOption"); request.getSession().setAttribute("selectValueSetSearchOption", selectValueSetSearchOption); String algorithm = (String) request.getParameter("valueset_search_algorithm"); request.getSession().setAttribute("valueset_search_algorithm", algorithm); System.out.println("(*** AjaxServlet ***) selectValueSetSearchOption ..." + selectValueSetSearchOption); System.out.println("(*** AjaxServlet ***) search_value_set ...algorithm " + algorithm); // check if any checkbox is checked. String contextPath = request.getContextPath(); String view_str = (String) request.getParameter("view"); int view = Integer.parseInt(view_str); String msg = null; request.getSession().removeAttribute("checked_vocabularies"); String checked_vocabularies = (String) request.getParameter("checked_vocabularies"); System.out.println("checked_vocabularies: " + checked_vocabularies); String matchText = (String) request.getParameter("matchText"); if (DataUtils.isNull(matchText)) { matchText = ""; } else { matchText = matchText.trim(); } request.getSession().setAttribute("matchText", matchText); System.out.println("(*** AjaxServlet ***) search_value_set ...matchText " + matchText); String ontology_display_name = (String) request.getParameter("ontology_display_name"); String ontology_version = (String) request.getParameter("ontology_version"); System.out.println("search_value_set ontology_display_name: " + ontology_display_name); System.out.println("search_value_set ontology_version: " + ontology_version); if (matchText.compareTo("") == 0) { msg = "Please enter a search string."; System.out.println(msg); request.getSession().setAttribute("message", msg); if (!DataUtils.isNull(ontology_display_name) && !DataUtils.isNull(ontology_version)) { create_vs_tree(request, response, view, ontology_display_name, ontology_version); } else { create_vs_tree(request, response, view); } return; } if (checked_vocabularies == null || (checked_vocabularies != null && checked_vocabularies.compareTo("") == 0)) { //DYEE msg = "No value set definition is selected."; System.out.println(msg); request.getSession().setAttribute("message", msg); if (!DataUtils.isNull(ontology_display_name) && !DataUtils.isNull(ontology_version)) { create_vs_tree(request, response, view, ontology_display_name, ontology_version); } else { create_vs_tree(request, response, view); } } else { String destination = contextPath + "/pages/value_set_search_results.jsf"; try { String retstr = valueSetSearchAction(request); //KLO, 041312 if (retstr.compareTo("message") == 0) { if (!DataUtils.isNull(ontology_display_name) && !DataUtils.isNull(ontology_version)) { create_vs_tree(request, response, view, ontology_display_name, ontology_version); } else { create_vs_tree(request, response, view); } return; } System.out.println("(*) redirecting to: " + destination); response.sendRedirect(response.encodeRedirectURL(destination)); request.getSession().setAttribute("checked_vocabularies", checked_vocabularies); } catch (Exception ex) { System.out.println("response.sendRedirect failed???"); } } } public static String valueSetSearchAction(HttpServletRequest request) { java.lang.String valueSetDefinitionRevisionId = null; String msg = null; String selectValueSetSearchOption = (String) request.getParameter("selectValueSetSearchOption"); if (DataUtils.isNull(selectValueSetSearchOption)) { selectValueSetSearchOption = "Name"; } request.getSession().setAttribute("selectValueSetSearchOption", selectValueSetSearchOption); String algorithm = (String) request.getParameter("valueset_search_algorithm"); if (DataUtils.isNull(algorithm)) { algorithm = "exactMatch"; } request.getSession().setAttribute("valueset_search_algorithm", algorithm); String checked_vocabularies = (String) request.getParameter("checked_vocabularies"); System.out.println("checked_vocabularies: " + checked_vocabularies); if (checked_vocabularies != null && checked_vocabularies.compareTo("") == 0) { msg = "No value set definition is selected."; System.out.println(msg); request.getSession().setAttribute("message", msg); return "message"; } Vector selected_vocabularies = new Vector(); selected_vocabularies = DataUtils.parseData(checked_vocabularies, ","); System.out.println("selected_vocabularies count: " + selected_vocabularies.size()); String VSD_view = (String) request.getParameter("view"); request.getSession().setAttribute("view", VSD_view); String matchText = (String) request.getParameter("matchText"); Vector v = new Vector(); LexEVSValueSetDefinitionServices vsd_service = null; vsd_service = RemoteServerUtil.getLexEVSValueSetDefinitionServices(); if (matchText != null) matchText = matchText.trim(); if (selectValueSetSearchOption.compareTo("Code") == 0) { String uri = null; try { String versionTag = null;//"PRODUCTION"; if (checked_vocabularies != null) { for (int k=0; k<selected_vocabularies.size(); k++) { String vsd_name = (String) selected_vocabularies.elementAt(k); String vsd_uri = DataUtils.getValueSetDefinitionURIByName(vsd_name); System.out.println("vsd_name: " + vsd_name + " (vsd_uri: " + vsd_uri + ")"); try { //ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(vsd_uri), null); if (vsd_uri != null) { ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(vsd_uri), null); AbsoluteCodingSchemeVersionReference acsvr = vsd_service.isEntityInValueSet(matchText, new URI(vsd_uri), null, versionTag); if (acsvr != null) { String metadata = DataUtils.getValueSetDefinitionMetadata(vsd); if (metadata != null) { v.add(metadata); } } } else { System.out.println("WARNING: Unable to find vsd_uri for " + vsd_name); } } catch (Exception ex) { System.out.println("WARNING: vsd_service.getValueSetDefinition threw exception: " + vsd_name); } } } else { AbsoluteCodingSchemeVersionReferenceList csVersionList = null;//ValueSetHierarchy.getAbsoluteCodingSchemeVersionReferenceList(); List list = vsd_service.listValueSetsWithEntityCode(matchText, null, csVersionList, versionTag); if (list != null) { for (int j=0; j<list.size(); j++) { uri = (String) list.get(j); String vsd_name = DataUtils.valueSetDefiniionURI2Name(uri); if (selected_vocabularies.contains(vsd_name)) { try { ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(uri), null); if (vsd == null) { msg = "Unable to find any value set with URI " + uri + "."; request.getSession().setAttribute("message", msg); return "message"; } String metadata = DataUtils.getValueSetDefinitionMetadata(vsd); if (metadata != null) { v.add(metadata); } } catch (Exception ex) { ex.printStackTrace(); msg = "Unable to find any value set with URI " + uri + "."; request.getSession().setAttribute("message", msg); return "message"; } } } } } request.getSession().setAttribute("matched_vsds", v); if (v.size() == 0) { msg = "No match found."; request.getSession().setAttribute("message", msg); return "message"; } else if (v.size() == 1) { request.getSession().setAttribute("vsd_uri", uri); } return "value_set"; } catch (Exception ex) { ex.printStackTrace(); System.out.println("vsd_service.listValueSetsWithEntityCode throws exceptions???"); } msg = "Unexpected errors encountered; search by code failed."; request.getSession().setAttribute("message", msg); return "message"; } else if (selectValueSetSearchOption.compareTo("Name") == 0) { String uri = null; try { Vector uri_vec = DataUtils.getValueSetURIs(); for (int i=0; i<uri_vec.size(); i++) { uri = (String) uri_vec.elementAt(i); String vsd_name = DataUtils.valueSetDefiniionURI2Name(uri); if (checked_vocabularies == null || selected_vocabularies.contains(vsd_name)) { //System.out.println("Searching " + vsd_name + "..."); AbsoluteCodingSchemeVersionReferenceList csVersionList = null; /* Vector cs_ref_vec = DataUtils.getCodingSchemeReferencesInValueSetDefinition(uri, "PRODUCTION"); if (cs_ref_vec != null) { csVersionList = DataUtils.vector2CodingSchemeVersionReferenceList(cs_ref_vec); } */ ResolvedValueSetCodedNodeSet rvs_cns = null; SortOptionList sortOptions = null; LocalNameList propertyNames = null; CodedNodeSet.PropertyType[] propertyTypes = null; try { System.out.println("URI: " + uri); rvs_cns = vsd_service.getValueSetDefinitionEntitiesForTerm(matchText, algorithm, new URI(uri), csVersionList, null); if (rvs_cns != null) { CodedNodeSet cns = rvs_cns.getCodedNodeSet(); ResolvedConceptReferencesIterator itr = cns.resolve(sortOptions, propertyNames, propertyTypes); if (itr != null && itr.numberRemaining() > 0) { AbsoluteCodingSchemeVersionReferenceList ref_list = rvs_cns.getCodingSchemeVersionRefList(); if (ref_list.getAbsoluteCodingSchemeVersionReferenceCount() > 0) { try { ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(uri), null); if (vsd == null) { msg = "Unable to find any value set with name " + matchText + "."; request.getSession().setAttribute("message", msg); return "message"; } String metadata = DataUtils.getValueSetDefinitionMetadata(vsd); if (metadata != null) { v.add(metadata); } } catch (Exception ex) { ex.printStackTrace(); msg = "Unable to find any value set with name " + matchText + "."; request.getSession().setAttribute("message", msg); return "message"; } } } } } catch (Exception ex) { //System.out.println("WARNING: getValueSetDefinitionEntitiesForTerm throws exception???"); msg = "getValueSetDefinitionEntitiesForTerm throws exception -- search by \"" + matchText + "\" failed. (VSD URI: " + uri + ")"; System.out.println(msg); request.getSession().setAttribute("message", msg); ex.printStackTrace(); return "message"; } } } request.getSession().setAttribute("matched_vsds", v); if (v.size() == 0) { msg = "No match found."; request.getSession().setAttribute("message", msg); return "message"; } else if (v.size() == 1) { request.getSession().setAttribute("vsd_uri", uri); } return "value_set"; } catch (Exception ex) { //ex.printStackTrace(); System.out.println("vsd_service.getValueSetDefinitionEntitiesForTerm throws exceptions???"); } msg = "Unexpected errors encountered; search by name failed."; request.getSession().setAttribute("message", msg); return "message"; } return "value_set"; } public static void create_vs_tree(HttpServletRequest request, HttpServletResponse response, int view, String dictionary, String version) { response.setContentType("text/html"); PrintWriter out = null; try { out = response.getWriter(); } catch (Exception ex) { ex.printStackTrace(); return; } String message = (String) request.getSession().getAttribute("message"); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"); out.println("<html xmlns:c=\"http://java.sun.com/jsp/jstl/core\">"); out.println("<head>"); out.println(" <title>" + dictionary + " value set</title>"); //out.println(" <title>NCI Thesaurus</title>"); out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"); out.println(""); out.println("<style type=\"text/css\">"); out.println("/*margin and padding on body element"); out.println(" can introduce errors in determining"); out.println(" element position and are not recommended;"); out.println(" we turn them off as a foundation for YUI"); out.println(" CSS treatments. */"); out.println("body {"); out.println(" margin:0;"); out.println(" padding:0;"); out.println("}"); out.println("</style>"); out.println(""); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/fonts/fonts-min.css\" />"); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/treeview/assets/skins/sam/treeview.css\" />"); out.println(""); out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>"); out.println(""); out.println(""); out.println("<!-- Dependency -->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js\"></script>"); out.println(""); out.println("<!-- Source file -->"); out.println("<!--"); out.println(" If you require only basic HTTP transaction support, use the"); out.println(" connection_core.js file."); out.println("-->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js\"></script>"); out.println(""); out.println("<!--"); out.println(" Use the full connection.js if you require the following features:"); out.println(" - Form serialization."); out.println(" - File Upload using the iframe transport."); out.println(" - Cross-domain(XDR) transactions."); out.println("-->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js\"></script>"); out.println(""); out.println(""); out.println(""); out.println("<!--begin custom header content for this example-->"); out.println("<!--Additional custom style rules for this example:-->"); out.println("<style type=\"text/css\">"); out.println(""); out.println(""); out.println(".ygtvcheck0 { background: url(/ncitbrowser/images/yui/treeview/check0.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(".ygtvcheck1 { background: url(/ncitbrowser/images/yui/treeview/check1.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(".ygtvcheck2 { background: url(/ncitbrowser/images/yui/treeview/check2.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(""); out.println(""); out.println(".ygtv-edit-TaskNode { width: 190px;}"); out.println(".ygtv-edit-TaskNode .ygtvcancel, .ygtv-edit-TextNode .ygtvok { border:none;}"); out.println(".ygtv-edit-TaskNode .ygtv-button-container { float: right;}"); out.println(".ygtv-edit-TaskNode .ygtv-input input{ width: 140px;}"); out.println(".whitebg {"); out.println(" background-color:white;"); out.println("}"); out.println("</style>"); out.println(""); out.println(" <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />"); out.println(" <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />"); out.println(""); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tasknode.js\"></script>"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/search.js\"></script>"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/dropdown.js\"></script>"); out.println(""); out.println(" <script type=\"text/javascript\">"); out.println(""); out.println(" function refresh() {"); out.println(""); out.println(" var selectValueSetSearchOptionObj = document.forms[\"valueSetSearchForm\"].selectValueSetSearchOption;"); out.println(""); out.println(" for (var i=0; i<selectValueSetSearchOptionObj.length; i++) {"); out.println(" if (selectValueSetSearchOptionObj[i].checked) {"); out.println(" selectValueSetSearchOption = selectValueSetSearchOptionObj[i].value;"); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(" window.location.href=\"/ncitbrowser/pages/value_set_source_view.jsf?refresh=1\""); out.println(" + \"&nav_type=valuesets\" + \"&opt=\"+ selectValueSetSearchOption;"); out.println(""); out.println(" }"); out.println(" </script>"); out.println(""); out.println(" <script language=\"JavaScript\">"); out.println(""); out.println(" var tree;"); out.println(" var nodeIndex;"); out.println(" var nodes = [];"); out.println(""); out.println(" function load(url,target) {"); out.println(" if (target != '')"); out.println(" target.window.location.href = url;"); out.println(" else"); out.println(" window.location.href = url;"); out.println(" }"); out.println(""); out.println(" function init() {"); out.println(" //initTree();"); out.println(" }"); out.println(""); out.println(" //handler for expanding all nodes"); out.println(" YAHOO.util.Event.on(\"expand_all\", \"click\", function(e) {"); out.println(" //expandEntireTree();"); out.println(""); out.println(" tree.expandAll();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for collapsing all nodes"); out.println(" YAHOO.util.Event.on(\"collapse_all\", \"click\", function(e) {"); out.println(" tree.collapseAll();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for checking all nodes"); out.println(" YAHOO.util.Event.on(\"check_all\", \"click\", function(e) {"); out.println(" check_all();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for unchecking all nodes"); out.println(" YAHOO.util.Event.on(\"uncheck_all\", \"click\", function(e) {"); out.println(" uncheck_all();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(""); out.println(""); out.println(" YAHOO.util.Event.on(\"getchecked\", \"click\", function(e) {"); out.println(" //alert(\"Checked nodes: \" + YAHOO.lang.dump(getCheckedNodes()), \"info\", \"example\");"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(""); out.println(" });"); out.println(""); out.println(""); out.println(" function addTreeNode(rootNode, nodeInfo) {"); out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); out.println(""); out.println(" if (nodeInfo.ontology_node_id.indexOf(\"TVS_\") >= 0) {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };"); out.println(" } else {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); out.println(" }"); out.println(""); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, false);"); out.println(" if (nodeInfo.ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function buildTree(ontology_node_id, ontology_display_name) {"); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" }"); out.println(" else {"); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" var expand = false;"); out.println(" //addTreeNode(root, nodeInfo, expand);"); out.println(""); out.println(" addTreeNode(root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" tree.draw();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_src_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function resetTree(ontology_node_id, ontology_display_name) {"); out.println(""); out.println(" var handleResetTreeSuccess = function(o) {"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(" if ( typeof(respObj.root_node) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";"); out.println(" var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };"); out.println(" var expand = false;"); out.println(" if (respObj.root_node.ontology_node_child_count > 0) {"); out.println(" expand = true;"); out.println(" }"); out.println(" var ontRoot = new YAHOO.widget.TaskNode(rootNodeData, root, expand);"); out.println(""); out.println(" if ( typeof(respObj.child_nodes) != \"undefined\") {"); out.println(" for (var i=0; i < respObj.child_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.child_nodes[i];"); out.println(" addTreeNode(ontRoot, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" tree.draw();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleResetTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var resetTreeCallback ="); out.println(" {"); out.println(" success:handleResetTreeSuccess,"); out.println(" failure:handleResetTreeFailure"); out.println(" };"); out.println(" if (ontology_node_id!= '') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function onClickTreeNode(ontology_node_id) {"); out.println(" //alert(\"onClickTreeNode \" + ontology_node_id);"); out.println(" window.location = '/ncitbrowser/pages/value_set_treenode_redirect.jsf?ontology_node_id=' + ontology_node_id;"); out.println(" }"); out.println(""); out.println(""); out.println(" function onClickViewEntireOntology(ontology_display_name) {"); out.println(" var ontology_display_name = document.pg_form.ontology_display_name.value;"); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(" function initTree() {"); out.println(""); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); //out.println(" pre_check();"); out.println(" tree.setNodesProperty('propagateHighlightUp',true);"); out.println(" tree.setNodesProperty('propagateHighlightDown',true);"); out.println(" tree.subscribe('keydown',tree._onKeyDownEvent);"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" tree.subscribe(\"expand\", function(node) {"); out.println(""); out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 39 });"); out.println(""); out.println(" });"); out.println(""); out.println(""); out.println(""); out.println(" tree.subscribe(\"collapse\", function(node) {"); out.println(" //alert(\"Collapsing \" + node.label );"); out.println(""); out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 109 });"); out.println(" });"); out.println(""); out.println(" // By default, trees with TextNodes will fire an event for when the label is clicked:"); out.println(" tree.subscribe(\"checkClick\", function(node) {"); out.println(" //alert(node.data.myNodeId + \" label was checked\");"); out.println(" });"); out.println(""); out.println(""); println(out, " var root = tree.getRoot();"); HashMap value_set_tree_hmap = DataUtils.getCodingSchemeValueSetTree(); TreeItem root = (TreeItem) value_set_tree_hmap.get("<Root>"); new ValueSetUtils().printTree(out, root, Constants.TERMINOLOGY_VIEW, dictionary); //new ValueSetUtils().printTree(out, root, Constants.TERMINOLOGY_VIEW); String contextPath = request.getContextPath(); String view_str = new Integer(view).toString(); //String option = (String) request.getSession().getAttribute("selectValueSetSearchOption"); //String algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm"); String option = (String) request.getParameter("selectValueSetSearchOption"); String algorithm = (String) request.getParameter("valueset_search_algorithm"); String option_code = ""; String option_name = ""; if (DataUtils.isNull(option)) { option_code = "checked"; } else { if (option.compareToIgnoreCase("Code") == 0) { option_code = "checked"; } if (option.compareToIgnoreCase("Name") == 0) { option_name = "checked"; } } String algorithm_exactMatch = ""; String algorithm_startsWith = ""; String algorithm_contains = ""; if (DataUtils.isNull(algorithm)) { algorithm_exactMatch = "checked"; } else { if (algorithm.compareToIgnoreCase("exactMatch") == 0) { algorithm_exactMatch = "checked"; } if (algorithm.compareToIgnoreCase("startsWith") == 0) { algorithm_startsWith = "checked"; } if (algorithm.compareToIgnoreCase("contains") == 0) { algorithm_contains = "checked"; } } out.println(""); if (message == null) { out.println(" tree.collapseAll();"); } out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(""); out.println(" function onCheckClick(node) {"); out.println(" YAHOO.log(node.label + \" check was clicked, new state: \" + node.checkState, \"info\", \"example\");"); out.println(" }"); out.println(""); out.println(" function check_all() {"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" topNodes[i].check();"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function uncheck_all() {"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" topNodes[i].uncheck();"); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(" function expand_all() {"); out.println(" //alert(\"expand_all\");"); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" onClickViewEntireOntology(ontology_display_name);"); out.println(" }"); out.println(""); out.println(" function pre_check() {"); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); //out.println(" alert(ontology_display_name);"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" if (topNodes[i].label == ontology_display_name) {"); out.println(" topNodes[i].check();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); // 0=unchecked, 1=some children checked, 2=all children checked out.println(" // Gets the labels of all of the fully checked nodes"); out.println(" // Could be updated to only return checked leaf nodes by evaluating"); out.println(" // the children collection first."); out.println(" function getCheckedNodes(nodes) {"); out.println(" nodes = nodes || tree.getRoot().children;"); out.println(" checkedNodes = [];"); out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {"); out.println(" var n = nodes[i];"); out.println(" if (n.checkState > 0) { // if we were interested in the nodes that have some but not all children checked"); out.println(" //if (n.checkState == 2) {"); out.println(" checkedNodes.push(n.label); // just using label for simplicity"); out.println(""); out.println(" if (n.hasChildren()) {"); out.println(" checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));"); out.println(" }"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(" var checked_vocabularies = document.forms[\"valueSetSearchForm\"].checked_vocabularies;"); out.println(" checked_vocabularies.value = checkedNodes;"); out.println(""); out.println(" return checkedNodes;"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" function loadNodeData(node, fnLoadComplete) {"); out.println(" var id = node.data.id;"); out.println(""); out.println(" var responseSuccess = function(o)"); out.println(" {"); out.println(" var path;"); out.println(" var dirs;"); out.println(" var files;"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" var fileNum = 0;"); out.println(" var categoryNum = 0;"); out.println(" if ( typeof(respObj.nodes) != \"undefined\") {"); out.println(" for (var i=0; i < respObj.nodes.length; i++) {"); out.println(" var name = respObj.nodes[i].ontology_node_name;"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, node, false);"); out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" tree.draw();"); out.println(" fnLoadComplete();"); out.println(" }"); out.println(""); out.println(" var responseFailure = function(o){"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var callback ="); out.println(" {"); out.println(" success:responseSuccess,"); out.println(" failure:responseFailure"); out.println(" };"); out.println(""); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_src_vs_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);"); out.println(" }"); out.println(""); out.println(""); out.println(" function searchTree(ontology_node_id, ontology_display_name) {"); out.println(""); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(""); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(""); out.println(" if ( typeof(respObj.dummy_root_nodes) != \"undefined\") {"); out.println(" showNodeNotFound(ontology_node_id);"); out.println(" }"); out.println(""); out.println(" else if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" }"); out.println(" else {"); out.println(" showPartialHierarchy();"); out.println(" showConstructingTreeStatus();"); out.println(""); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" //var expand = false;"); out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;//document.pg_form.ontology_source.value;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=search_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(" function expandEntireTree() {"); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" //tree.draw();"); out.println(""); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;"); out.println(""); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(""); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(""); out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(""); out.println(" //alert(respObj.root_nodes.length);"); out.println(""); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" } else {"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" //alert(\"calling addTreeBranch \");"); out.println(""); out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_entire_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {"); out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); out.println(""); out.println(" var newNodeData;"); out.println(" if (ontology_node_id.indexOf(\"TVS_\") >= 0) {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };"); out.println(" } else {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); out.println(" }"); out.println(""); out.println(" var expand = false;"); out.println(" var childNodes = nodeInfo.children_nodes;"); out.println(""); out.println(" if (childNodes.length > 0) {"); out.println(" expand = true;"); out.println(" }"); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, expand);"); out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {"); out.println(" newNode.labelStyle = \"ygtvlabel_highlight\";"); out.println(" }"); out.println(""); out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {"); out.println(" newNode.isLeaf = true;"); out.println(" if (nodeInfo.ontology_node_child_count > 0) {"); out.println(" newNode.isLeaf = false;"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" } else {"); out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(" } else {"); out.println(" if (nodeInfo.ontology_node_id != ontology_node_id) {"); out.println(" if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {"); out.println(" newNode.isLeaf = true;"); out.println(" } else if (childNodes.length == 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" tree.draw();"); out.println(" for (var i=0; i < childNodes.length; i++) {"); out.println(" var childnodeInfo = childNodes[i];"); out.println(" addTreeBranch(ontology_node_id, newNode, childnodeInfo);"); out.println(" }"); out.println(" }"); out.println(" YAHOO.util.Event.addListener(window, \"load\", init);"); out.println(""); out.println(" YAHOO.util.Event.onDOMReady(initTree);"); out.println(""); out.println(""); out.println(" </script>"); out.println(""); out.println("</head>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); //out.println("<body>"); out.println("<body onLoad=\"document.forms.valueSetSearchForm.matchText.focus();\">"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/wz_tooltip.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_centerwindow.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_followscroll.js\"></script>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" <!-- Begin Skip Top Navigation -->"); out.println(" <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>"); out.println(" <!-- End Skip Top Navigation -->"); out.println(""); out.println("<!-- nci banner -->"); out.println("<div class=\"ncibanner\">"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/logotype.gif\""); out.println(" width=\"440\" height=\"39\" border=\"0\""); out.println(" alt=\"National Cancer Institute\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/spacer.gif\""); out.println(" width=\"48\" height=\"39\" border=\"0\""); out.println(" alt=\"National Cancer Institute\" class=\"print-header\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.nih.gov\" target=\"_blank\" >"); out.println(" <img src=\"/ncitbrowser/images/tagline_nologo.gif\""); out.println(" width=\"173\" height=\"39\" border=\"0\""); out.println(" alt=\"U.S. National Institutes of Health\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/cancer-gov.gif\""); out.println(" width=\"99\" height=\"39\" border=\"0\""); out.println(" alt=\"www.cancer.gov\"/>"); out.println(" </a>"); out.println("</div>"); out.println("<!-- end nci banner -->"); out.println(""); out.println(" <div class=\"center-page\">"); out.println(" <!-- EVS Logo -->"); out.println("<div>"); // to be modified out.println(" <img src=\"/ncitbrowser/images/evs-logo-swapped.gif\" alt=\"EVS Logo\""); out.println(" width=\"745\" height=\"26\" border=\"0\""); out.println(" usemap=\"#external-evs\" />"); out.println(" <map id=\"external-evs\" name=\"external-evs\">"); out.println(" <area shape=\"rect\" coords=\"0,0,140,26\""); out.println(" href=\"/ncitbrowser/start.jsf\" target=\"_self\""); out.println(" alt=\"NCI Term Browser\" />"); out.println(" <area shape=\"rect\" coords=\"520,0,745,26\""); out.println(" href=\"http://evs.nci.nih.gov/\" target=\"_blank\""); out.println(" alt=\"Enterprise Vocabulary Services\" />"); out.println(" </map>"); out.println("</div>"); out.println(""); out.println(""); out.println("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"); out.println(" <tr>"); out.println(" <td width=\"5\"></td>"); //to be modified out.println(" <td><a href=\"/ncitbrowser/pages/multiple_search.jsf?nav_type=terminologies\">"); out.println(" <img name=\"tab_terms\" src=\"/ncitbrowser/images/tab_terms_clicked.gif\""); out.println(" border=\"0\" alt=\"Terminologies\" title=\"Terminologies\" /></a></td>"); out.println(" <td><a href=\"/ncitbrowser/ajax?action=create_src_vs_tree\">"); out.println(" <img name=\"tab_valuesets\" src=\"/ncitbrowser/images/tab_valuesets.gif\""); out.println(" border=\"0\" alt=\"Value Sets\" title=\"ValueSets\" /></a></td>"); out.println(" <td><a href=\"/ncitbrowser/pages/mapping_search.jsf?nav_type=mappings\">"); out.println(" <img name=\"tab_map\" src=\"/ncitbrowser/images/tab_map.gif\""); out.println(" border=\"0\" alt=\"Mappings\" title=\"Mappings\" /></a></td>"); out.println(" </tr>"); out.println("</table>"); out.println(""); out.println("<div class=\"mainbox-top\"><img src=\"/ncitbrowser/images/mainbox-top.gif\" width=\"745\" height=\"5\" alt=\"\"/></div>"); out.println("<!-- end EVS Logo -->"); out.println(" <!-- Main box -->"); out.println(" <div id=\"main-area\">"); out.println(""); out.println(" <!-- Thesaurus, banner search area -->"); out.println(" <div class=\"bannerarea\">"); /* out.println(" <a href=\"/ncitbrowser/start.jsf\" style=\"text-decoration: none;\">"); out.println(" <div class=\"vocabularynamebanner_tb\">"); out.println(" <span class=\"vocabularynamelong_tb\">" + JSPUtils.getApplicationVersionDisplay() + "</span>"); out.println(" </div>"); out.println(" </a>"); */ JSPUtils.JSPHeaderInfoMore info = new JSPUtils.JSPHeaderInfoMore(request); String scheme = info.dictionary; String term_browser_version = info.term_browser_version; String display_name = info.display_name; String basePath = request.getContextPath(); /* <a href="/ncitbrowser/pages/home.jsf?version=12.02d" style="text-decoration: none;"> <div class="vocabularynamebanner_ncit"> <span class="vocabularynamelong_ncit">Version: 12.02d (Release date: 2012-02-27-08:00)</span> </div> </a> */ String release_date = DataUtils.getVersionReleaseDate(scheme, version); if (dictionary != null && dictionary.compareTo("NCI Thesaurus") == 0) { out.println("<a href=\"/ncitbrowser/pages/home.jsf?version=" + version + "\" style=\"text-decoration: none;\">"); out.println(" <div class=\"vocabularynamebanner_ncit\">"); out.println(" <span class=\"vocabularynamelong_ncit\">Version: " + version + " (Release date: " + release_date + ")</span>"); out.println(" </div>"); out.println("</a>"); /* out.write("\r\n"); out.write(" <div class=\"banner\"><a href=\""); out.print(basePath); out.write("\"><img src=\""); out.print(basePath); out.write("/images/thesaurus_browser_logo.jpg\" width=\"383\" height=\"117\" alt=\"Thesaurus Browser Logo\" border=\"0\"/></a></div>\r\n"); */ } else { out.write("\r\n"); out.write("\r\n"); out.write(" "); if (version == null) { out.write("\r\n"); out.write(" <a class=\"vocabularynamebanner\" href=\""); out.print(request.getContextPath()); out.write("/pages/vocabulary.jsf?dictionary="); out.print(HTTPUtils.cleanXSS(dictionary)); out.write("\">\r\n"); out.write(" "); } else { out.write("\r\n"); out.write(" <a class=\"vocabularynamebanner\" href=\""); out.print(request.getContextPath()); out.write("/pages/vocabulary.jsf?dictionary="); out.print(HTTPUtils.cleanXSS(dictionary)); out.write("&version="); out.print(HTTPUtils.cleanXSS(version)); out.write("\">\r\n"); out.write(" "); } out.write("\r\n"); out.write(" <div class=\"vocabularynamebanner\">\r\n"); out.write(" <div class=\"vocabularynameshort\" STYLE=\"font-size: "); out.print(HTTPUtils.maxFontSize(display_name)); out.write("px; font-family : Arial\">\r\n"); out.write(" "); out.print(HTTPUtils.cleanXSS(display_name)); out.write("\r\n"); out.write(" </div>\r\n"); out.write(" \r\n"); boolean display_release_date = true; if (release_date == null || release_date.compareTo("") == 0) { display_release_date = false; } if (display_release_date) { out.write("\r\n"); out.write(" <div class=\"vocabularynamelong\">Version: "); out.print(HTTPUtils.cleanXSS(term_browser_version)); out.write(" (Release date: "); out.print(release_date); out.write(")</div>\r\n"); } else { out.write("\r\n"); out.write(" <div class=\"vocabularynamelong\">Version: "); out.print(HTTPUtils.cleanXSS(term_browser_version)); out.write("</div>\r\n"); } out.write(" \r\n"); out.write(" \r\n"); out.write(" </div>\r\n"); out.write(" </a>\r\n"); } out.println(" <div class=\"search-globalnav\">"); out.println(" <!-- Search box -->"); out.println(" <div class=\"searchbox-top\"><img src=\"/ncitbrowser/images/searchbox-top.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Top\" /></div>"); out.println(" <div class=\"searchbox\">"); out.println(""); out.println(""); out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + "/ajax?action=search_value_set\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">"); out.println("<input type=\"hidden\" name=\"valueSetSearchForm\" value=\"valueSetSearchForm\" />"); out.println("<input type=\"hidden\" name=\"view\" value=\"" + view_str + "\" />"); String matchText = (String) request.getSession().getAttribute("matchText"); if (DataUtils.isNull(matchText)) { matchText = ""; } out.println(""); out.println(""); out.println(""); out.println(" <input type=\"hidden\" id=\"checked_vocabularies\" name=\"checked_vocabularies\" value=\"\" />"); out.println(""); out.println(""); out.println(""); out.println("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 2px\" >"); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(""); out.println(" <input CLASS=\"searchbox-input-2\""); out.println(" name=\"matchText\""); out.println(" value=\"" + matchText + "\""); out.println(" onFocus=\"active = true\""); out.println(" onBlur=\"active = false\""); out.println(" onkeypress=\"return submitEnter('valueSetSearchForm:valueset_search',event)\""); out.println(" tabindex=\"1\"/>"); out.println(""); out.println(""); out.println(" <input id=\"valueSetSearchForm:valueset_search\" type=\"image\" src=\"/ncitbrowser/images/search.gif\" name=\"valueSetSearchForm:valueset_search\" alt=\"Search Value Sets\" onclick=\"javascript:getCheckedNodes();\" tabindex=\"2\" class=\"searchbox-btn\" /><a href=\"/ncitbrowser/pages/help.jsf#searchhelp\" tabindex=\"3\"><img src=\"/ncitbrowser/images/search-help.gif\" alt=\"Search Help\" style=\"border-width:0;\" class=\"searchbox-btn\" /></a>"); out.println(""); out.println(""); out.println(" </td>"); out.println(" </tr>"); out.println(""); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td>"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 0px\">"); out.println(""); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"exactMatch\" alt=\"Exact Match\" " + algorithm_exactMatch + " tabindex=\"3\">Exact Match&nbsp;"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"startsWith\" alt=\"Begins With\" " + algorithm_startsWith + " tabindex=\"3\">Begins With&nbsp;"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"contains\" alt=\"Contains\" " + algorithm_contains + " tabindex=\"3\">Contains"); out.println(" </td>"); out.println(" </tr>"); out.println(""); out.println(" <tr align=\"left\">"); out.println(" <td height=\"1px\" bgcolor=\"#2F2F5F\" align=\"left\"></td>"); out.println(" </tr>"); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Code\" " + option_code + " alt=\"Code\" tabindex=\"1\" >Code&nbsp;"); out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Name\" " + option_name + " alt=\"Name\" tabindex=\"1\" >Name"); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(" </td>"); out.println(" </tr>"); out.println("</table>"); out.println(" <input type=\"hidden\" name=\"referer\" id=\"referer\" value=\"http%3A%2F%2Flocalhost%3A8080%2Fncitbrowser%2Fpages%2Fresolved_value_set_search_results.jsf\">"); out.println(" <input type=\"hidden\" id=\"nav_type\" name=\"nav_type\" value=\"valuesets\" />"); out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />"); out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"" + dictionary + "\" />"); out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"" + dictionary + "\" />"); out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"" + version + "\" />"); out.println(""); out.println("<input type=\"hidden\" name=\"javax.faces.ViewState\" id=\"javax.faces.ViewState\" value=\"j_id22:j_id23\" />"); out.println("</form>"); out.println(" </div> <!-- searchbox -->"); out.println(""); out.println(" <div class=\"searchbox-bottom\"><img src=\"/ncitbrowser/images/searchbox-bottom.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Bottom\" /></div>"); out.println(" <!-- end Search box -->"); out.println(" <!-- Global Navigation -->"); out.println(""); /* out.println("<table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">"); out.println(" <tr>"); out.println(" <td align=\"left\" valign=\"bottom\">"); out.println(" <a href=\"#\" onclick=\"javascript:window.open('/ncitbrowser/pages/source_help_info-termbrowser.jsf',"); out.println(" '_blank','top=100, left=100, height=740, width=780, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"13\">"); out.println(" Sources</a>"); out.println(""); out.println(" \r\n"); out.println(" "); out.print( VisitedConceptUtils.getDisplayLink(request, true) ); out.println(" \r\n"); out.println(" </td>"); out.println(" <td align=\"right\" valign=\"bottom\">"); out.println(" <a href=\""); out.print( request.getContextPath() ); out.println("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n"); out.println(" </td>\r\n"); out.println(" <td width=\"7\"></td>\r\n"); out.println(" </tr>\r\n"); out.println("</table>"); */ boolean hasValueSet = ValueSetHierarchy.hasValueSet(scheme); boolean hasMapping = DataUtils.hasMapping(scheme); boolean tree_access_allowed = true; if (DataUtils._vocabulariesWithoutTreeAccessHashSet.contains(scheme)) { tree_access_allowed = false; } boolean vocabulary_isMapping = DataUtils.isMapping(scheme, null); out.write(" <table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">\r\n"); out.write(" <tr>\r\n"); out.write(" <td valign=\"bottom\">\r\n"); out.write(" "); Boolean[] isPipeDisplayed = new Boolean[] { Boolean.FALSE }; out.write("\r\n"); out.write(" "); if (vocabulary_isMapping) { out.write("\r\n"); out.write(" "); out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) ); out.write("\r\n"); out.write(" <a href=\""); out.print(request.getContextPath() ); out.write("/pages/mapping.jsf?dictionary="); out.print(HTTPUtils.cleanXSS(scheme)); out.write("&version="); out.print(version); out.write("\">\r\n"); out.write(" Mapping\r\n"); out.write(" </a>\r\n"); out.write(" "); } else if (tree_access_allowed) { out.write("\r\n"); out.write(" "); out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) ); out.write("\r\n"); out.write(" <a href=\"#\" onclick=\"javascript:window.open('"); out.print(request.getContextPath()); out.write("/pages/hierarchy.jsf?dictionary="); out.print(HTTPUtils.cleanXSS(scheme)); out.write("&version="); out.print(HTTPUtils.cleanXSS(version)); out.write("', '_blank','top=100, left=100, height=740, width=680, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"12\">\r\n"); out.write(" Hierarchy </a>\r\n"); out.write(" "); } out.write(" \r\n"); out.write(" \r\n"); out.write(" \r\n"); out.write(" "); if (hasValueSet) { out.write("\r\n"); out.write(" "); out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) ); out.write("\r\n"); out.write(" <!--\r\n"); out.write(" <a href=\""); out.print( request.getContextPath() ); out.write("/pages/value_set_hierarchy.jsf?dictionary="); out.print(HTTPUtils.cleanXSS(scheme)); out.write("&version="); out.print(HTTPUtils.cleanXSS(version)); out.write("\" tabindex=\"15\">Value Sets</a>\r\n"); out.write(" -->\r\n"); out.write(" <a href=\""); out.print( request.getContextPath() ); out.write("/ajax?action=create_cs_vs_tree&dictionary="); out.print(HTTPUtils.cleanXSS(scheme)); out.write("&version="); out.print(HTTPUtils.cleanXSS(version)); out.write("\" tabindex=\"15\">Value Sets</a>\r\n"); out.write("\r\n"); out.write("\r\n"); out.write(" "); } out.write("\r\n"); out.write(" \r\n"); out.write(" "); if (hasMapping) { out.write("\r\n"); out.write(" "); out.print( JSPUtils.getPipeSeparator(isPipeDisplayed) ); out.write("\r\n"); out.write(" <a href=\""); out.print( request.getContextPath() ); out.write("/pages/cs_mappings.jsf?dictionary="); out.print(HTTPUtils.cleanXSS(scheme)); out.write("&version="); out.print(HTTPUtils.cleanXSS(version)); out.write("\" tabindex=\"15\">Maps</a> \r\n"); out.write(" "); } out.write(" "); out.print( VisitedConceptUtils.getDisplayLink(request, isPipeDisplayed) ); out.write("\r\n"); out.write(" </td>\r\n"); out.write(" <td align=\"right\" valign=\"bottom\">\r\n"); out.write(" <a href=\""); out.print(request.getContextPath()); out.write("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n"); out.write(" </td>\r\n"); out.write(" <td width=\"7\" valign=\"bottom\"></td>\r\n"); out.write(" </tr>\r\n"); out.write(" </table>\r\n"); out.println(" <!-- end Global Navigation -->"); out.println(""); out.println(" </div> <!-- search-globalnav -->"); out.println(" </div> <!-- bannerarea -->"); out.println(""); out.println(" <!-- end Thesaurus, banner search area -->"); out.println(" <!-- Quick links bar -->"); out.println(""); out.println("<div class=\"bluebar\">"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); out.println(" <tr>"); out.println(" <td><div class=\"quicklink-status\">&nbsp;</div></td>"); out.println(" <td>"); out.println(""); /* out.println(" <div id=\"quicklinksholder\">"); out.println(" <ul id=\"quicklinks\""); out.println(" onmouseover=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-active.gif';\""); out.println(" onmouseout=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-inactive.gif';\">"); out.println(" <li>"); out.println(" <a href=\"#\" tabindex=\"-1\"><img src=\"/ncitbrowser/images/quicklinks-inactive.gif\" width=\"162\""); out.println(" height=\"18\" border=\"0\" name=\"quicklinksimg\" alt=\"Quick Links\" />"); out.println(" </a>"); out.println(" <ul>"); out.println(" <li><a href=\"http://evs.nci.nih.gov/\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"Enterprise Vocabulary Services\">EVS Home</a></li>"); out.println(" <li><a href=\"http://localhost/ncimbrowserncimbrowser\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"NCI Metathesaurus\">NCI Metathesaurus Browser</a></li>"); out.println(""); out.println(" <li><a href=\"/ncitbrowser/start.jsf\" tabindex=\"-1\""); out.println(" alt=\"NCI Term Browser\">NCI Term Browser</a></li>"); out.println(" <li><a href=\"http://www.cancer.gov/cancertopics/terminologyresources\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"NCI Terminology Resources\">NCI Terminology Resources</a></li>"); out.println(""); out.println(" <li><a href=\"http://ncitermform.nci.nih.gov/ncitermform/?dictionary=NCI%20Thesaurus\" tabindex=\"-1\" target=\"_blank\" alt=\"Term Suggestion\">Term Suggestion</a></li>"); out.println(""); out.println(""); out.println(" </ul>"); out.println(" </li>"); out.println(" </ul>"); out.println(" </div>"); */ addQuickLink(request, out); out.println(""); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(""); out.println("</div>"); if (! ServerMonitorThread.getInstance().isLexEVSRunning()) { out.println(" <div class=\"redbar\">"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); out.println(" <tr>"); out.println(" <td class=\"lexevs-status\">"); out.println(" " + ServerMonitorThread.getInstance().getMessage()); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(" </div>"); } out.println(" <!-- end Quick links bar -->"); out.println(""); out.println(" <!-- Page content -->"); out.println(" <div class=\"pagecontent\">"); out.println(""); if (message != null) { out.println("\r\n"); out.println(" <p class=\"textbodyred\">"); out.print(message); out.println("</p>\r\n"); out.println(" "); request.getSession().removeAttribute("message"); } // to be modified /* out.println("<p class=\"textbody\">"); out.println("View value sets organized by standards category or source terminology."); out.println("Standards categories group the value sets supporting them; all other labels lead to the home pages of actual value sets or source terminologies."); out.println("Search or browse a value set from its home page, or search all value sets at once from this page (very slow) to find which ones contain a particular code or term."); out.println("</p>"); */ out.println(""); out.println(" <div id=\"popupContentArea\">"); out.println(" <a name=\"evs-content\" id=\"evs-content\"></a>"); out.println(""); out.println(" <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" <tr class=\"textbody\">"); out.println(" <td class=\"textbody\" align=\"left\">"); out.println(""); /* if (view == Constants.STANDARD_VIEW) { out.println(" Standards View"); out.println(" &nbsp;|"); out.println(" <a href=\"" + contextPath + "/ajax?action=create_cs_vs_tree\">Terminology View</a>"); } else { out.println(" <a href=\"" + contextPath + "/ajax?action=create_src_vs_tree\">Standards View</a>"); out.println(" &nbsp;|"); out.println(" Terminology View"); } */ out.println(" </td>"); out.println(""); out.println(" <td align=\"right\">"); out.println(" <font size=\"1\" color=\"red\" align=\"right\">"); out.println(" <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>"); out.println(" </font>"); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(""); out.println(" <hr/>"); out.println(""); out.println(""); out.println(""); out.println("<style>"); out.println("#expandcontractdiv {border:1px solid #336600; background-color:#FFFFCC; margin:0 0 .5em 0; padding:0.2em;}"); out.println("#treecontainer { background: #fff }"); out.println("</style>"); out.println(""); out.println(""); out.println("<div id=\"expandcontractdiv\">"); out.println(" <a id=\"expand_all\" href=\"#\">Expand all</a>"); out.println(" <a id=\"collapse_all\" href=\"#\">Collapse all</a>"); out.println(" <a id=\"check_all\" href=\"#\">Check all</a>"); out.println(" <a id=\"uncheck_all\" href=\"#\">Uncheck all</a>"); out.println("</div>"); out.println(""); out.println(""); out.println(""); out.println(" <!-- Tree content -->"); out.println(""); out.println(" <div id=\"treecontainer\" class=\"ygtv-checkbox\"></div>"); out.println(""); out.println(" <form id=\"pg_form\">"); out.println(""); out.println(" <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"" + dictionary + "\" />"); out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"" + dictionary + "\" />"); out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"" + version + "\" />"); out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />"); out.println(" </form>"); out.println(""); out.println(""); out.println(" </div> <!-- popupContentArea -->"); out.println(""); out.println(""); out.println("<div class=\"textbody\">"); out.println("<!-- footer -->"); out.println("<div class=\"footer\" style=\"width:720px\">"); out.println(" <ul>"); out.println(" <li><a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\">NCI Home</a> |</li>"); out.println(" <li><a href=\"/ncitbrowser/pages/contact_us.jsf\">Contact Us</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies\" target=\"_blank\" alt=\"National Cancer Institute Policies\">Policies</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies/page3\" target=\"_blank\" alt=\"National Cancer Institute Accessibility\">Accessibility</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies/page6\" target=\"_blank\" alt=\"National Cancer Institute FOIA\">FOIA</a></li>"); out.println(" </ul>"); out.println(" <p>"); out.println(" A Service of the National Cancer Institute<br />"); out.println(" <img src=\"/ncitbrowser/images/external-footer-logos.gif\""); out.println(" alt=\"External Footer Logos\" width=\"238\" height=\"34\" border=\"0\""); out.println(" usemap=\"#external-footer\" />"); out.println(" </p>"); out.println(" <map id=\"external-footer\" name=\"external-footer\">"); out.println(" <area shape=\"rect\" coords=\"0,0,46,34\""); out.println(" href=\"http://www.cancer.gov\" target=\"_blank\""); out.println(" alt=\"National Cancer Institute\" />"); out.println(" <area shape=\"rect\" coords=\"55,1,99,32\""); out.println(" href=\"http://www.hhs.gov/\" target=\"_blank\""); out.println(" alt=\"U.S. Health &amp; Human Services\" />"); out.println(" <area shape=\"rect\" coords=\"103,1,147,31\""); out.println(" href=\"http://www.nih.gov/\" target=\"_blank\""); out.println(" alt=\"National Institutes of Health\" />"); out.println(" <area shape=\"rect\" coords=\"148,1,235,33\""); out.println(" href=\"http://www.usa.gov/\" target=\"_blank\""); out.println(" alt=\"USA.gov\" />"); out.println(" </map>"); out.println("</div>"); out.println("<!-- end footer -->"); out.println("</div>"); out.println(""); out.println(""); out.println(" </div> <!-- pagecontent -->"); out.println(" </div> <!-- main-area -->"); out.println(" <div class=\"mainbox-bottom\"><img src=\"/ncitbrowser/images/mainbox-bottom.gif\" width=\"745\" height=\"5\" alt=\"Mainbox Bottom\" /></div>"); out.println(""); out.println(" </div> <!-- center-page -->"); out.println(""); out.println("</body>"); out.println("</html>"); out.println(""); } public static void addQuickLink(HttpServletRequest request, PrintWriter out) { String basePath = request.getContextPath(); String ncim_url = new DataUtils().getNCImURL(); String quicklink_dictionary = (String) request.getSession().getAttribute("dictionary"); quicklink_dictionary = DataUtils.getFormalName(quicklink_dictionary); String term_suggestion_application_url2 = ""; String dictionary_encoded2 = ""; if (quicklink_dictionary != null) { term_suggestion_application_url2 = DataUtils.getMetadataValue(quicklink_dictionary, "term_suggestion_application_url"); dictionary_encoded2 = DataUtils.replaceAll(quicklink_dictionary, " ", "%20"); } out.write(" <div id=\"quicklinksholder\">\r\n"); out.write(" <ul id=\"quicklinks\"\r\n"); out.write(" onmouseover=\"document.quicklinksimg.src='"); out.print(basePath); out.write("/images/quicklinks-active.gif';\"\r\n"); out.write(" onmouseout=\"document.quicklinksimg.src='"); out.print(basePath); out.write("/images/quicklinks-inactive.gif';\">\r\n"); out.write(" <li>\r\n"); out.write(" <a href=\"#\" tabindex=\"-1\"><img src=\""); out.print(basePath); out.write("/images/quicklinks-inactive.gif\" width=\"162\"\r\n"); out.write(" height=\"18\" border=\"0\" name=\"quicklinksimg\" alt=\"Quick Links\" />\r\n"); out.write(" </a>\r\n"); out.write(" <ul>\r\n"); out.write(" <li><a href=\"http://evs.nci.nih.gov/\" tabindex=\"-1\" target=\"_blank\"\r\n"); out.write(" alt=\"Enterprise Vocabulary Services\">EVS Home</a></li>\r\n"); out.write(" <li><a href=\""); out.print(ncim_url); out.write("\" tabindex=\"-1\" target=\"_blank\"\r\n"); out.write(" alt=\"NCI Metathesaurus\">NCI Metathesaurus Browser</a></li>\r\n"); out.write("\r\n"); out.write(" "); if (quicklink_dictionary == null || quicklink_dictionary.compareTo("NCI Thesaurus") != 0) { out.write("\r\n"); out.write("\r\n"); out.write(" <li><a href=\""); out.print( request.getContextPath() ); out.write("/index.jsp\" tabindex=\"-1\"\r\n"); out.write(" alt=\"NCI Thesaurus Browser\">NCI Thesaurus Browser</a></li>\r\n"); out.write("\r\n"); out.write(" "); } out.write("\r\n"); out.write("\r\n"); out.write(" <li>\r\n"); out.write(" <a href=\""); out.print( request.getContextPath() ); out.write("/termbrowser.jsf\" tabindex=\"-1\" alt=\"NCI Term Browser\">NCI Term Browser</a>\r\n"); out.write(" </li>\r\n"); out.write(" \r\n"); out.write(" <li><a href=\"http://www.cancer.gov/cancertopics/terminologyresources\" tabindex=\"-1\" target=\"_blank\"\r\n"); out.write(" alt=\"NCI Terminology Resources\">NCI Terminology Resources</a></li>\r\n"); out.write(" "); if (term_suggestion_application_url2 != null && term_suggestion_application_url2.length() > 0) { out.write("\r\n"); out.write(" <li><a href=\""); out.print(term_suggestion_application_url2); out.write("?dictionary="); out.print(dictionary_encoded2); out.write("\" tabindex=\"-1\" target=\"_blank\" alt=\"Term Suggestion\">Term Suggestion</a></li>\r\n"); out.write(" "); } out.write("\r\n"); out.write("\r\n"); out.write(" </ul>\r\n"); out.write(" </li>\r\n"); out.write(" </ul>\r\n"); out.write(" </div>\r\n"); } }
[GF#31914] Search option and algorithm in value set search box are not preserved in session. [KLO, 041812] git-svn-id: 8a910031c78bbe8a754298bb28800c1494820db3@2893 0604bb77-1110-461e-859e-28c50bf9b280
software/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AjaxServlet.java
[GF#31914] Search option and algorithm in value set search box are not preserved in session. [KLO, 041812]
<ide><path>oftware/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AjaxServlet.java <ide> //String algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm"); <ide> <ide> String option = (String) request.getParameter("selectValueSetSearchOption"); <add>if (DataUtils.isNull(option)) { <add> option = (String) request.getSession().getAttribute("selectValueSetSearchOption"); <add>} <add> <add>if (DataUtils.isNull(option)) { <add> option = "Code"; <add>} <add>request.getSession().setAttribute("selectValueSetSearchOption", option); <add> <add> <add> <ide> String algorithm = (String) request.getParameter("valueset_search_algorithm"); <add>if (DataUtils.isNull(algorithm)) { <add> algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm"); <add>} <add> <add>if (DataUtils.isNull(algorithm)) { <add> algorithm = "exactMatch"; <add>} <add>request.getSession().setAttribute("valueset_search_algorithm", algorithm); <add> <add> <add> <add> <ide> <ide> <ide> String matchText = (String) request.getParameter("matchText");
Java
bsd-3-clause
2f2ed334609592c5af9f322e2fbe0772ecff3d14
0
ClemsonRSRG/RESOLVE,ClemsonRSRG/RESOLVE,NighatYasmin/RESOLVE,yushan87/RESOLVE,NighatYasmin/RESOLVE,ClemsonRSRG/RESOLVE,yushan87/RESOLVE,NighatYasmin/RESOLVE,yushan87/RESOLVE
/** * HardCoded.java * --------------------------------- * Copyright (c) 2016 * RESOLVE Software Research Group * School of Computing * Clemson University * All rights reserved. * --------------------------------- * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ package edu.clemson.cs.rsrg.typeandpopulate.utilities; import edu.clemson.cs.rsrg.absyn.clauses.AssertionClause; import edu.clemson.cs.rsrg.absyn.clauses.AssertionClause.ClauseType; import edu.clemson.cs.rsrg.absyn.declarations.Dec; import edu.clemson.cs.rsrg.absyn.declarations.moduledecl.FacilityModuleDec; import edu.clemson.cs.rsrg.absyn.declarations.moduledecl.ModuleDec; import edu.clemson.cs.rsrg.absyn.declarations.paramdecl.ModuleParameterDec; import edu.clemson.cs.rsrg.absyn.expressions.Exp; import edu.clemson.cs.rsrg.absyn.expressions.mathexpr.VarExp; import edu.clemson.cs.rsrg.absyn.items.programitems.UsesItem; import edu.clemson.cs.rsrg.init.file.ModuleType; import edu.clemson.cs.rsrg.init.file.ResolveFile; import edu.clemson.cs.rsrg.parsing.data.Location; import edu.clemson.cs.rsrg.parsing.data.PosSymbol; import edu.clemson.cs.rsrg.statushandling.StatusHandler; import edu.clemson.cs.rsrg.statushandling.exception.MiscErrorException; import edu.clemson.cs.rsrg.typeandpopulate.entry.SymbolTableEntry.Quantification; import edu.clemson.cs.rsrg.typeandpopulate.exception.DuplicateSymbolException; import edu.clemson.cs.rsrg.typeandpopulate.mathtypes.MTFunction; import edu.clemson.cs.rsrg.typeandpopulate.mathtypes.MTNamed; import edu.clemson.cs.rsrg.typeandpopulate.mathtypes.MTPowertypeApplication; import edu.clemson.cs.rsrg.typeandpopulate.mathtypes.MTType; import edu.clemson.cs.rsrg.typeandpopulate.symboltables.MathSymbolTableBuilder; import edu.clemson.cs.rsrg.typeandpopulate.symboltables.ScopeBuilder; import edu.clemson.cs.rsrg.typeandpopulate.typereasoning.TypeGraph; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import org.antlr.v4.runtime.ANTLRInputStream; /** * <p>The <code>HardCoded</code> class defines all mathematical symbols * and relationships that cannot be put into a {@code Precis} module.</p> * * @version 2.0 */ public class HardCoded { /** * <p>Since all of our {@link StatusHandler} requires a {@link Location} to work * properly, we create an object pointing to an input stream that is empty. * Subsequently, we use this object to create all of our built in type information.</p> */ private static final Location NATIVE_FILE_FAKE_LOCATION; static { try { NATIVE_FILE_FAKE_LOCATION = new Location(new ResolveFile("native", ModuleType.THEORY, new ANTLRInputStream(new StringReader("")), new ArrayList<String>(), ""), 0, 0, ""); } catch (IOException e) { throw new MiscErrorException("Error instantiating native file", e); } } /** * <p>This method establishes all built-in relationships of the symbol table.</p> * * @param g The current type graph. * @param b The current scope repository builder. */ public static void addBuiltInRelationships(TypeGraph g, MathSymbolTableBuilder b) { try { //This is just a hard-coded version of this theoretical type theorem //that can't actually appear in a theory because it won't type-check //(it requires itself to typecheck): //Type Theorem Function_Subtypes: // For all D1, R1 : MType, // For all D2 : Powerset(D1), // For all R2 : Powerset(R1), // For all f : D2 -> R2, // f : D1 -> R1; AssertionClause requires = new AssertionClause(NATIVE_FILE_FAKE_LOCATION, ClauseType.REQUIRES, VarExp.getTrueVarExp( NATIVE_FILE_FAKE_LOCATION, g)); ModuleDec module = new FacilityModuleDec(NATIVE_FILE_FAKE_LOCATION, new PosSymbol(NATIVE_FILE_FAKE_LOCATION, "native"), new ArrayList<ModuleParameterDec>(), new ArrayList<UsesItem>(), requires, new ArrayList<Dec>(), new HashMap<PosSymbol, Boolean>()); VarExp v = new VarExp(NATIVE_FILE_FAKE_LOCATION, null, new PosSymbol( NATIVE_FILE_FAKE_LOCATION, "native")); ScopeBuilder s = b.startModuleScope(module); s.addBinding("D1", Quantification.UNIVERSAL, v, g.CLS); s.addBinding("R1", Quantification.UNIVERSAL, v, g.CLS); s.addBinding("D2", Quantification.UNIVERSAL, v, new MTPowertypeApplication(g, new MTNamed(g, "D1"))); s.addBinding("R2", Quantification.UNIVERSAL, v, new MTPowertypeApplication(g, new MTNamed(g, "R1"))); s.addBinding("f", Quantification.UNIVERSAL, v, new MTFunction(g, new MTNamed(g, "R2"), new MTNamed(g, "D2"))); VarExp f = new VarExp(null, null, new PosSymbol(null, "f"), Quantification.UNIVERSAL); f.setMathType(new MTFunction(g, new MTNamed(g, "R2"), new MTNamed( g, "D2"))); g.addRelationship(f, new MTFunction(g, new MTNamed(g, "R1"), new MTNamed(g, "D1")), null, s); b.endScope(); } catch (DuplicateSymbolException dse) { //Not possible--we're the first ones to add anything throw new RuntimeException(dse); } } /** * <p>This method establishes all built-in symbols of the symbol table.</p> * * @param g The current type graph. * @param b The current scope repository builder. */ public static void addBuiltInSymbols(TypeGraph g, ScopeBuilder b) { VarExp v = new VarExp(NATIVE_FILE_FAKE_LOCATION, null, new PosSymbol( NATIVE_FILE_FAKE_LOCATION, "native")); try { b.addBinding("Entity", v, g.CLS, g.ENTITY); b.addBinding("Cls", v, g.CLS, g.CLS); b.addBinding("Instance_Of", v, new MTFunction(g, g.BOOLEAN, g.CLS, g.ENTITY)); b.addBinding("SSet", v, g.CLS, g.SET); b.addBinding("B", v, g.CLS, g.BOOLEAN); b.addBinding("Empty_Set", v, g.CLS, g.EMPTY_SET); b.addBinding("Powerset", v, g.POWERTYPE); b.addBinding("Powerclass", v, g.POWERCLASS); b.addBinding("true", v, g.BOOLEAN); b.addBinding("false", v, g.BOOLEAN); b.addBinding("cls_union", v, g.UNION); b.addBinding("cls_intersection", v, g.INTERSECT); b.addBinding("->", v, g.FUNCTION); b.addBinding("and", v, g.AND); b.addBinding("not", v, g.NOT); b.addBinding("*", v, g.CROSS); b.addBinding("=", v, new MTFunction(g, g.BOOLEAN, g.ENTITY, g.ENTITY)); b.addBinding("/=", v, new MTFunction(g, g.BOOLEAN, g.ENTITY, g.ENTITY)); b.addBinding("or", v, new MTFunction(g, g.BOOLEAN, g.BOOLEAN, g.BOOLEAN)); } catch (DuplicateSymbolException dse) { //Not possible--we're the first ones to add anything throw new RuntimeException(dse); } } /** * <p>This method returns the mathematical function used to represent an * expression's meta-segment.</p> * * @param g The current type graph. * @param e An {@link Exp}. * @param metaSegment A string representing a meta-segment for * <code>e</code>. * * @return A {@link MTType} if we can establish its type, * <code>null</code> otherwise. */ public static MTType getMetaFieldType(TypeGraph g, Exp e, String metaSegment) { MTType result = null; if (e.getMathTypeValue() != null && metaSegment.equals("Is_Initial")) { result = new MTFunction(g, g.BOOLEAN, g.ENTITY); } return result; } }
src/main/java/edu/clemson/cs/rsrg/typeandpopulate/utilities/HardCoded.java
/** * HardCoded.java * --------------------------------- * Copyright (c) 2016 * RESOLVE Software Research Group * School of Computing * Clemson University * All rights reserved. * --------------------------------- * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ package edu.clemson.cs.rsrg.typeandpopulate.utilities; import edu.clemson.cs.rsrg.absyn.clauses.AssertionClause; import edu.clemson.cs.rsrg.absyn.clauses.AssertionClause.ClauseType; import edu.clemson.cs.rsrg.absyn.declarations.Dec; import edu.clemson.cs.rsrg.absyn.declarations.moduledecl.FacilityModuleDec; import edu.clemson.cs.rsrg.absyn.declarations.moduledecl.ModuleDec; import edu.clemson.cs.rsrg.absyn.declarations.paramdecl.ModuleParameterDec; import edu.clemson.cs.rsrg.absyn.expressions.Exp; import edu.clemson.cs.rsrg.absyn.expressions.mathexpr.VarExp; import edu.clemson.cs.rsrg.absyn.items.programitems.UsesItem; import edu.clemson.cs.rsrg.parsing.data.PosSymbol; import edu.clemson.cs.rsrg.typeandpopulate.entry.SymbolTableEntry.Quantification; import edu.clemson.cs.rsrg.typeandpopulate.exception.DuplicateSymbolException; import edu.clemson.cs.rsrg.typeandpopulate.mathtypes.MTFunction; import edu.clemson.cs.rsrg.typeandpopulate.mathtypes.MTNamed; import edu.clemson.cs.rsrg.typeandpopulate.mathtypes.MTPowertypeApplication; import edu.clemson.cs.rsrg.typeandpopulate.mathtypes.MTType; import edu.clemson.cs.rsrg.typeandpopulate.symboltables.MathSymbolTableBuilder; import edu.clemson.cs.rsrg.typeandpopulate.symboltables.ScopeBuilder; import edu.clemson.cs.rsrg.typeandpopulate.typereasoning.TypeGraph; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; /** * <p>The <code>HardCoded</code> class defines all mathematical symbols * and relationships that cannot be put into a {@code Precis} module.</p> * * @version 2.0 */ public class HardCoded { /** * <p>This method establishes all built-in relationships of the symbol table.</p> * * @param g The current type graph. * @param b The current scope repository builder. */ public static void addBuiltInRelationships(TypeGraph g, MathSymbolTableBuilder b) { try { //This is just a hard-coded version of this theoretical type theorem //that can't actually appear in a theory because it won't type-check //(it requires itself to typecheck): //Type Theorem Function_Subtypes: // For all D1, R1 : MType, // For all D2 : Powerset(D1), // For all R2 : Powerset(R1), // For all f : D2 -> R2, // f : D1 -> R1; AssertionClause requires = new AssertionClause(null, ClauseType.REQUIRES, VarExp .getTrueVarExp(null, g)); ModuleDec module = new FacilityModuleDec(null, new PosSymbol(null, "native"), new ArrayList<ModuleParameterDec>(), new ArrayList<UsesItem>(), requires, new ArrayList<Dec>(), new HashMap<PosSymbol, Boolean>()); VarExp v = new VarExp(null, null, new PosSymbol(null, "native")); ScopeBuilder s = b.startModuleScope(module); s.addBinding("D1", Quantification.UNIVERSAL, v, g.CLS); s.addBinding("R1", Quantification.UNIVERSAL, v, g.CLS); s.addBinding("D2", Quantification.UNIVERSAL, v, new MTPowertypeApplication(g, new MTNamed(g, "D1"))); s.addBinding("R2", Quantification.UNIVERSAL, v, new MTPowertypeApplication(g, new MTNamed(g, "R1"))); s.addBinding("f", Quantification.UNIVERSAL, v, new MTFunction(g, new MTNamed(g, "R2"), new MTNamed(g, "D2"))); VarExp f = new VarExp(null, null, new PosSymbol(null, "f"), Quantification.UNIVERSAL); f.setMathType(new MTFunction(g, new MTNamed(g, "R2"), new MTNamed( g, "D2"))); g.addRelationship(f, new MTFunction(g, new MTNamed(g, "R1"), new MTNamed(g, "D1")), null, s); b.endScope(); } catch (DuplicateSymbolException dse) { //Not possible--we're the first ones to add anything throw new RuntimeException(dse); } } /** * <p>This method establishes all built-in symbols of the symbol table.</p> * * @param g The current type graph. * @param b The current scope repository builder. */ public static void addBuiltInSymbols(TypeGraph g, ScopeBuilder b) { VarExp v = new VarExp(null, null, new PosSymbol(null, "native")); try { b.addBinding("Entity", v, g.CLS, g.ENTITY); b.addBinding("Cls", v, g.CLS, g.CLS); b.addBinding("Instance_Of", v, new MTFunction(g, g.BOOLEAN, g.CLS, g.ENTITY)); b.addBinding("SSet", v, g.CLS, g.SET); b.addBinding("B", v, g.CLS, g.BOOLEAN); b.addBinding("Empty_Set", v, g.CLS, g.EMPTY_SET); b.addBinding("Powerset", v, g.POWERTYPE); b.addBinding("Powerclass", v, g.POWERCLASS); b.addBinding("true", v, g.BOOLEAN); b.addBinding("false", v, g.BOOLEAN); b.addBinding("cls_union", v, g.UNION); b.addBinding("cls_intersection", v, g.INTERSECT); b.addBinding("->", v, g.FUNCTION); b.addBinding("and", v, g.AND); b.addBinding("not", v, g.NOT); b.addBinding("*", v, g.CROSS); b.addBinding("=", v, new MTFunction(g, g.BOOLEAN, g.ENTITY, g.ENTITY)); b.addBinding("/=", v, new MTFunction(g, g.BOOLEAN, g.ENTITY, g.ENTITY)); b.addBinding("or", v, new MTFunction(g, g.BOOLEAN, g.BOOLEAN, g.BOOLEAN)); } catch (DuplicateSymbolException dse) { //Not possible--we're the first ones to add anything throw new RuntimeException(dse); } } /** * <p>This method returns the mathematical function used to represent an * expression's meta-segment.</p> * * @param g The current type graph. * @param e An {@link Exp}. * @param metaSegment A string representing a meta-segment for * <code>e</code>. * * @return A {@link MTType} if we can establish its type, * <code>null</code> otherwise. */ public static MTType getMetaFieldType(TypeGraph g, Exp e, String metaSegment) { MTType result = null; if (e.getMathTypeValue() != null && metaSegment.equals("Is_Initial")) { result = new MTFunction(g, g.BOOLEAN, g.ENTITY); } return result; } }
Created a fake ResolveFile object for the built in math logic
src/main/java/edu/clemson/cs/rsrg/typeandpopulate/utilities/HardCoded.java
Created a fake ResolveFile object for the built in math logic
<ide><path>rc/main/java/edu/clemson/cs/rsrg/typeandpopulate/utilities/HardCoded.java <ide> import edu.clemson.cs.rsrg.absyn.expressions.Exp; <ide> import edu.clemson.cs.rsrg.absyn.expressions.mathexpr.VarExp; <ide> import edu.clemson.cs.rsrg.absyn.items.programitems.UsesItem; <add>import edu.clemson.cs.rsrg.init.file.ModuleType; <add>import edu.clemson.cs.rsrg.init.file.ResolveFile; <add>import edu.clemson.cs.rsrg.parsing.data.Location; <ide> import edu.clemson.cs.rsrg.parsing.data.PosSymbol; <add>import edu.clemson.cs.rsrg.statushandling.StatusHandler; <add>import edu.clemson.cs.rsrg.statushandling.exception.MiscErrorException; <ide> import edu.clemson.cs.rsrg.typeandpopulate.entry.SymbolTableEntry.Quantification; <ide> import edu.clemson.cs.rsrg.typeandpopulate.exception.DuplicateSymbolException; <ide> import edu.clemson.cs.rsrg.typeandpopulate.mathtypes.MTFunction; <ide> import edu.clemson.cs.rsrg.typeandpopulate.symboltables.MathSymbolTableBuilder; <ide> import edu.clemson.cs.rsrg.typeandpopulate.symboltables.ScopeBuilder; <ide> import edu.clemson.cs.rsrg.typeandpopulate.typereasoning.TypeGraph; <add>import java.io.IOException; <add>import java.io.StringReader; <ide> import java.util.ArrayList; <ide> import java.util.HashMap; <del>import java.util.HashSet; <add>import org.antlr.v4.runtime.ANTLRInputStream; <ide> <ide> /** <ide> * <p>The <code>HardCoded</code> class defines all mathematical symbols <ide> public class HardCoded { <ide> <ide> /** <add> * <p>Since all of our {@link StatusHandler} requires a {@link Location} to work <add> * properly, we create an object pointing to an input stream that is empty. <add> * Subsequently, we use this object to create all of our built in type information.</p> <add> */ <add> private static final Location NATIVE_FILE_FAKE_LOCATION; <add> <add> static { <add> try { <add> NATIVE_FILE_FAKE_LOCATION = <add> new Location(new ResolveFile("native", ModuleType.THEORY, <add> new ANTLRInputStream(new StringReader("")), <add> new ArrayList<String>(), ""), 0, 0, ""); <add> } <add> catch (IOException e) { <add> throw new MiscErrorException("Error instantiating native file", e); <add> } <add> } <add> <add> /** <ide> * <p>This method establishes all built-in relationships of the symbol table.</p> <ide> * <ide> * @param g The current type graph. <ide> // f : D1 -> R1; <ide> <ide> AssertionClause requires = <del> new AssertionClause(null, ClauseType.REQUIRES, VarExp <del> .getTrueVarExp(null, g)); <add> new AssertionClause(NATIVE_FILE_FAKE_LOCATION, <add> ClauseType.REQUIRES, VarExp.getTrueVarExp( <add> NATIVE_FILE_FAKE_LOCATION, g)); <ide> ModuleDec module = <del> new FacilityModuleDec(null, new PosSymbol(null, "native"), <add> new FacilityModuleDec(NATIVE_FILE_FAKE_LOCATION, <add> new PosSymbol(NATIVE_FILE_FAKE_LOCATION, "native"), <ide> new ArrayList<ModuleParameterDec>(), <ide> new ArrayList<UsesItem>(), requires, <ide> new ArrayList<Dec>(), <ide> new HashMap<PosSymbol, Boolean>()); <ide> <del> VarExp v = new VarExp(null, null, new PosSymbol(null, "native")); <add> VarExp v = <add> new VarExp(NATIVE_FILE_FAKE_LOCATION, null, new PosSymbol( <add> NATIVE_FILE_FAKE_LOCATION, "native")); <ide> ScopeBuilder s = b.startModuleScope(module); <ide> <ide> s.addBinding("D1", Quantification.UNIVERSAL, v, g.CLS); <ide> * @param b The current scope repository builder. <ide> */ <ide> public static void addBuiltInSymbols(TypeGraph g, ScopeBuilder b) { <del> VarExp v = new VarExp(null, null, new PosSymbol(null, "native")); <add> VarExp v = <add> new VarExp(NATIVE_FILE_FAKE_LOCATION, null, new PosSymbol( <add> NATIVE_FILE_FAKE_LOCATION, "native")); <ide> <ide> try { <ide> b.addBinding("Entity", v, g.CLS, g.ENTITY);
Java
bsd-2-clause
3fabe9752d69a3021278d9bdd3eed9a4d3d6417e
0
MattDevo/edk2,MattDevo/edk2,MattDevo/edk2,MattDevo/edk2,MattDevo/edk2,MattDevo/edk2,MattDevo/edk2,MattDevo/edk2
/** @file PlatformPcdPreprocessActionForBuilding class. This action class is to collect PCD information from MSA, SPD, FPD xml file. This class will be used for wizard and build tools, So it can *not* inherit from buildAction or wizardAction. Copyright (c) 2006, Intel Corporation All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ package org.tianocore.build.pcd.action; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.tianocore.DynamicPcdBuildDefinitionsDocument.DynamicPcdBuildDefinitions; import org.tianocore.PcdBuildDefinitionDocument; import org.tianocore.PlatformSurfaceAreaDocument; import org.tianocore.build.exception.PlatformPcdPreprocessBuildException; import org.tianocore.build.global.GlobalData; import org.tianocore.build.id.FpdModuleIdentification; import org.tianocore.pcd.action.PlatformPcdPreprocessAction; import org.tianocore.pcd.entity.MemoryDatabaseManager; import org.tianocore.pcd.entity.ModulePcdInfoFromFpd; import org.tianocore.pcd.entity.Token; import org.tianocore.pcd.entity.UsageIdentification; import org.tianocore.pcd.exception.EntityException; import org.tianocore.pcd.exception.PlatformPcdPreprocessException; /** This action class is to collect PCD information from MSA, SPD, FPD xml file. This class will be used for wizard and build tools, So it can *not* inherit from buildAction or UIAction. **/ public class PlatformPcdPreprocessActionForBuilding extends PlatformPcdPreprocessAction { /// /// FPD file path. /// private String fpdFilePath; /// /// Cache the fpd docment instance for private usage. /// private PlatformSurfaceAreaDocument fpdDocInstance; /** Set FPDFileName parameter for this action class. @param fpdFilePath fpd file path **/ public void setFPDFilePath(String fpdFilePath) { this.fpdFilePath = fpdFilePath; } /** Common function interface for outer. @param fpdFilePath The fpd file path of current build or processing. @throws PlatformPreprocessBuildException The exception of this function. Because it can *not* be predict where the action class will be used. So only Exception can be throw. **/ public void perform(String fpdFilePath) throws PlatformPcdPreprocessBuildException { this.fpdFilePath = fpdFilePath; checkParameter(); execute(); } /** Core execution function for this action class. This function work flows will be: 1) Collect and prepocess PCD information from FPD file, all PCD information will be stored into memory database. 2) Generate 3 strings for a) All modules using Dynamic(Ex) PCD entry.(Token Number) b) PEI PCDDatabase (C Structure) for PCD Service PEIM. c) DXE PCD Database (C structure) for PCD Service DXE. @throws EntityException Exception indicate failed to execute this action. **/ public void execute() throws PlatformPcdPreprocessBuildException { String errorMessageHeader = "Failed to initialize the Pcd memory database because: "; String errorsForPreprocess = null; // // Get memoryDatabaseManager instance from GlobalData. // The memoryDatabaseManager should be initialized as static variable // in some Pre-process class. // setPcdDbManager(GlobalData.getPCDMemoryDBManager()); // // Collect all PCD information defined in FPD file. // Evenry token defind in FPD will be created as an token into // memory database. // try { initPcdMemoryDbWithPlatformInfo(); } catch (PlatformPcdPreprocessException exp) { throw new PlatformPcdPreprocessBuildException(errorMessageHeader + exp.getMessage()); } errorsForPreprocess = this.getErrorString(); if (errorsForPreprocess != null) { throw new PlatformPcdPreprocessBuildException(errorMessageHeader + "\r\n" + errorsForPreprocess); } // // Generate for PEI, DXE PCD DATABASE's definition and initialization. // try { genPcdDatabaseSourceCode (); } catch (EntityException exp) { throw new PlatformPcdPreprocessBuildException(errorMessageHeader + "\r\n" + exp.getMessage()); } } /** Override function: implementate the method of get Guid string information from SPD file. @param guidCName Guid CName string. @return String Guid information from SPD file. **/ public String getGuidInfoFromSpd(String guidCName) { return GlobalData.getGuidInfoFromCname(guidCName); } /** This function generates source code for PCD Database. @throws EntityException If the token does *not* exist in memory database. **/ private void genPcdDatabaseSourceCode() throws EntityException { String PcdCommonHeaderString = PcdDatabase.getPcdDatabaseCommonDefinitions(); ArrayList<Token> alPei = new ArrayList<Token> (); ArrayList<Token> alDxe = new ArrayList<Token> (); getPcdDbManager().getTwoPhaseDynamicRecordArray(alPei, alDxe); PcdDatabase pcdPeiDatabase = new PcdDatabase (alPei, "PEI", 0); pcdPeiDatabase.genCode(); MemoryDatabaseManager.PcdPeimHString = PcdCommonHeaderString + pcdPeiDatabase.getHString() + PcdDatabase.getPcdPeiDatabaseDefinitions(); MemoryDatabaseManager.PcdPeimCString = pcdPeiDatabase.getCString(); PcdDatabase pcdDxeDatabase = new PcdDatabase(alDxe, "DXE", alPei.size()); pcdDxeDatabase.genCode(); MemoryDatabaseManager.PcdDxeHString = MemoryDatabaseManager.PcdPeimHString + pcdDxeDatabase.getHString() + PcdDatabase.getPcdDxeDatabaseDefinitions(); MemoryDatabaseManager.PcdDxeCString = pcdDxeDatabase.getCString(); } /** Override function: Get component array from FPD. This function maybe provided by some Global class. @return List<ModuleInfo> the component array. @throws PlatformPcdPreprocessException get all modules in <ModuleSA> in FPD file. **/ public List<ModulePcdInfoFromFpd> getComponentsFromFpd() throws PlatformPcdPreprocessException { List<ModulePcdInfoFromFpd> allModules = new ArrayList<ModulePcdInfoFromFpd>(); Map<FpdModuleIdentification, XmlObject> pcdBuildDefinitions = null; UsageIdentification usageId = null; pcdBuildDefinitions = GlobalData.getFpdPcdBuildDefinitions(); if (pcdBuildDefinitions == null) { return null; } // // Loop map to retrieve all PCD build definition and Module id // Iterator item = pcdBuildDefinitions.keySet().iterator(); while (item.hasNext()){ FpdModuleIdentification id = (FpdModuleIdentification) item.next(); usageId = new UsageIdentification(id.getModule().getName(), id.getModule().getGuid(), id.getModule().getPackage().getName(), id.getModule().getPackage().getGuid(), id.getArch(), id.getModule().getVersion(), id.getModule().getModuleType()); allModules.add( new ModulePcdInfoFromFpd( usageId, ((PcdBuildDefinitionDocument)pcdBuildDefinitions.get(id)).getPcdBuildDefinition())); } return allModules; } /** Override function: Verify the datum value according its datum size and datum type, this function maybe moved to FPD verification tools in future. @param cName The token name @param moduleName The module who use this PCD token @param datum The PCD's datum @param datumType The PCD's datum type @param maxDatumSize The max size for PCD's Datum. @return String exception strings. */ public String verifyDatum(String cName, String moduleName, String datum, Token.DATUM_TYPE datumType, int maxDatumSize) { // // In building system, datum should not be checked, the checking work // should be done by wizard tools or PCD verification tools. // return null; } /** Override function: Get dynamic information for a dynamic PCD from <DynamicPcdBuildDefinition> seciton in FPD file. This function should be implemented in GlobalData in future. @param token The token instance which has hold module's PCD information @param moduleName The name of module who will use this Dynamic PCD. @return DynamicPcdBuildDefinitions.PcdBuildData **/ public DynamicPcdBuildDefinitions.PcdBuildData getDynamicInfoFromFpd(Token token, String moduleName) throws PlatformPcdPreprocessException { int index = 0; String exceptionString = null; String dynamicPrimaryKey = null; DynamicPcdBuildDefinitions dynamicPcdBuildDefinitions = null; List<DynamicPcdBuildDefinitions.PcdBuildData> dynamicPcdBuildDataArray = null; String tokenSpaceStrRet = null; // // If FPD document is not be opened, open and initialize it. // BUGBUG: The code should be moved into GlobalData in future. // if (fpdDocInstance == null) { try { fpdDocInstance = (PlatformSurfaceAreaDocument)XmlObject.Factory.parse(new File(fpdFilePath)); } catch(IOException ioE) { throw new PlatformPcdPreprocessException("File IO error for xml file:" + fpdFilePath + "\n" + ioE.getMessage()); } catch(XmlException xmlE) { throw new PlatformPcdPreprocessException("Can't parse the FPD xml fle:" + fpdFilePath + "\n" + xmlE.getMessage()); } } dynamicPcdBuildDefinitions = fpdDocInstance.getPlatformSurfaceArea().getDynamicPcdBuildDefinitions(); if (dynamicPcdBuildDefinitions == null) { exceptionString = String.format("[FPD file error] There are no <PcdDynamicBuildDescriptions> elements in FPD file but there are Dynamic type "+ "PCD entries %s in module %s!", token.cName, moduleName); putError(exceptionString); return null; } dynamicPcdBuildDataArray = dynamicPcdBuildDefinitions.getPcdBuildDataList(); for (index = 0; index < dynamicPcdBuildDataArray.size(); index ++) { tokenSpaceStrRet = getGuidInfoFromSpd(dynamicPcdBuildDataArray.get(index).getTokenSpaceGuidCName()); if (tokenSpaceStrRet == null) { exceptionString = "Fail to get token space guid for token " + dynamicPcdBuildDataArray.get(index).getCName(); putError(exceptionString); continue; } dynamicPrimaryKey = Token.getPrimaryKeyString(dynamicPcdBuildDataArray.get(index).getCName(), tokenSpaceStrRet); if (dynamicPrimaryKey.equals(token.getPrimaryKeyString())) { return dynamicPcdBuildDataArray.get(index); } } return null; } /** Override function: get all <DynamicPcdBuildDefinition> from FPD file. @return List<DynamicPcdBuildDefinitions.PcdBuildData> All DYNAMIC PCD list in <DynamicPcdBuildDefinitions> in FPD file. @throws PlatformPcdPreprocessBuildException Failure to get dynamic information list. **/ public List<DynamicPcdBuildDefinitions.PcdBuildData> getAllDynamicPcdInfoFromFpd() throws PlatformPcdPreprocessException { DynamicPcdBuildDefinitions dynamicPcdBuildDefinitions = null; // // Open fpd document to get <DynamicPcdBuildDefinition> Section. // BUGBUG: the function should be move GlobalData in furture. // if (fpdDocInstance == null) { try { fpdDocInstance = (PlatformSurfaceAreaDocument)XmlObject.Factory.parse(new File(fpdFilePath)); } catch(IOException ioE) { throw new PlatformPcdPreprocessException("File IO error for xml file:" + fpdFilePath + "\n" + ioE.getMessage()); } catch(XmlException xmlE) { throw new PlatformPcdPreprocessException("Can't parse the FPD xml fle:" + fpdFilePath + "\n" + xmlE.getMessage()); } } dynamicPcdBuildDefinitions = fpdDocInstance.getPlatformSurfaceArea().getDynamicPcdBuildDefinitions(); if (dynamicPcdBuildDefinitions == null) { return null; } return dynamicPcdBuildDefinitions.getPcdBuildDataList(); } /** check parameter for this action. @throws PlatformPcdPreprocessBuildException Bad parameter. **/ private void checkParameter() throws PlatformPcdPreprocessBuildException { File file = null; if (fpdFilePath == null) { throw new PlatformPcdPreprocessBuildException("FPDFileName should be empty for CollectPCDAtion!"); } if (fpdFilePath.length() == 0) { throw new PlatformPcdPreprocessBuildException("FPDFileName should be empty for CollectPCDAtion!"); } file = new File(fpdFilePath); if(!file.exists()) { throw new PlatformPcdPreprocessBuildException("FPD File " + fpdFilePath + " does not exist!"); } } }
Tools/Java/Source/GenBuild/org/tianocore/build/pcd/action/PlatformPcdPreprocessActionForBuilding.java
/** @file PlatformPcdPreprocessActionForBuilding class. This action class is to collect PCD information from MSA, SPD, FPD xml file. This class will be used for wizard and build tools, So it can *not* inherit from buildAction or wizardAction. Copyright (c) 2006, Intel Corporation All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ package org.tianocore.build.pcd.action; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.tianocore.DynamicPcdBuildDefinitionsDocument.DynamicPcdBuildDefinitions; import org.tianocore.PcdBuildDefinitionDocument; import org.tianocore.PlatformSurfaceAreaDocument; import org.tianocore.build.exception.PlatformPcdPreprocessBuildException; import org.tianocore.build.global.GlobalData; import org.tianocore.build.id.FpdModuleIdentification; import org.tianocore.pcd.action.PlatformPcdPreprocessAction; import org.tianocore.pcd.entity.MemoryDatabaseManager; import org.tianocore.pcd.entity.ModulePcdInfoFromFpd; import org.tianocore.pcd.entity.Token; import org.tianocore.pcd.entity.UsageIdentification; import org.tianocore.pcd.exception.EntityException; import org.tianocore.pcd.exception.PlatformPcdPreprocessException; /** This action class is to collect PCD information from MSA, SPD, FPD xml file. This class will be used for wizard and build tools, So it can *not* inherit from buildAction or UIAction. **/ public class PlatformPcdPreprocessActionForBuilding extends PlatformPcdPreprocessAction { /// /// FPD file path. /// private String fpdFilePath; /// /// Cache the fpd docment instance for private usage. /// private PlatformSurfaceAreaDocument fpdDocInstance; /** Set FPDFileName parameter for this action class. @param fpdFilePath fpd file path **/ public void setFPDFilePath(String fpdFilePath) { this.fpdFilePath = fpdFilePath; } /** Common function interface for outer. @param fpdFilePath The fpd file path of current build or processing. @throws PlatformPreprocessBuildException The exception of this function. Because it can *not* be predict where the action class will be used. So only Exception can be throw. **/ public void perform(String fpdFilePath) throws PlatformPcdPreprocessBuildException { this.fpdFilePath = fpdFilePath; checkParameter(); execute(); } /** Core execution function for this action class. This function work flows will be: 1) Collect and prepocess PCD information from FPD file, all PCD information will be stored into memory database. 2) Generate 3 strings for a) All modules using Dynamic(Ex) PCD entry.(Token Number) b) PEI PCDDatabase (C Structure) for PCD Service PEIM. c) DXE PCD Database (C structure) for PCD Service DXE. @throws EntityException Exception indicate failed to execute this action. **/ public void execute() throws PlatformPcdPreprocessBuildException { String errorMessageHeader = "Failed to initialize the Pcd memory database because: "; String errorsForPreprocess = null; // // Get memoryDatabaseManager instance from GlobalData. // The memoryDatabaseManager should be initialized as static variable // in some Pre-process class. // setPcdDbManager(GlobalData.getPCDMemoryDBManager()); // // Collect all PCD information defined in FPD file. // Evenry token defind in FPD will be created as an token into // memory database. // try { initPcdMemoryDbWithPlatformInfo(); } catch (PlatformPcdPreprocessException exp) { throw new PlatformPcdPreprocessBuildException(errorMessageHeader + exp.getMessage()); } errorsForPreprocess = this.getErrorString(); if (errorsForPreprocess != null) { throw new PlatformPcdPreprocessBuildException(errorMessageHeader + "\r\n" + errorsForPreprocess); } // // Generate for PEI, DXE PCD DATABASE's definition and initialization. // try { genPcdDatabaseSourceCode (); } catch (EntityException exp) { throw new PlatformPcdPreprocessBuildException(errorMessageHeader + "\r\n" + exp.getMessage()); } } /** Override function: implementate the method of get Guid string information from SPD file. @param guidCName Guid CName string. @return String Guid information from SPD file. @throws PlatformPcdPreprocessException Fail to get Guid information from SPD file. **/ public String getGuidInfoFromSpd(String guidCName) throws PlatformPcdPreprocessException { String tokenSpaceStrRet = null; try { tokenSpaceStrRet = GlobalData.getGuidInfoFromCname(guidCName); } catch ( Exception e ) { throw new PlatformPcdPreprocessException ("Failed to get Guid CName " + guidCName + " from the SPD file!"); } return tokenSpaceStrRet; } /** This function generates source code for PCD Database. @throws EntityException If the token does *not* exist in memory database. **/ private void genPcdDatabaseSourceCode() throws EntityException { String PcdCommonHeaderString = PcdDatabase.getPcdDatabaseCommonDefinitions(); ArrayList<Token> alPei = new ArrayList<Token> (); ArrayList<Token> alDxe = new ArrayList<Token> (); getPcdDbManager().getTwoPhaseDynamicRecordArray(alPei, alDxe); PcdDatabase pcdPeiDatabase = new PcdDatabase (alPei, "PEI", 0); pcdPeiDatabase.genCode(); MemoryDatabaseManager.PcdPeimHString = PcdCommonHeaderString + pcdPeiDatabase.getHString() + PcdDatabase.getPcdPeiDatabaseDefinitions(); MemoryDatabaseManager.PcdPeimCString = pcdPeiDatabase.getCString(); PcdDatabase pcdDxeDatabase = new PcdDatabase(alDxe, "DXE", alPei.size()); pcdDxeDatabase.genCode(); MemoryDatabaseManager.PcdDxeHString = MemoryDatabaseManager.PcdPeimHString + pcdDxeDatabase.getHString() + PcdDatabase.getPcdDxeDatabaseDefinitions(); MemoryDatabaseManager.PcdDxeCString = pcdDxeDatabase.getCString(); } /** Override function: Get component array from FPD. This function maybe provided by some Global class. @return List<ModuleInfo> the component array. @throws PlatformPcdPreprocessException get all modules in <ModuleSA> in FPD file. **/ public List<ModulePcdInfoFromFpd> getComponentsFromFpd() throws PlatformPcdPreprocessException { List<ModulePcdInfoFromFpd> allModules = new ArrayList<ModulePcdInfoFromFpd>(); Map<FpdModuleIdentification, XmlObject> pcdBuildDefinitions = null; UsageIdentification usageId = null; pcdBuildDefinitions = GlobalData.getFpdPcdBuildDefinitions(); if (pcdBuildDefinitions == null) { return null; } // // Loop map to retrieve all PCD build definition and Module id // Iterator item = pcdBuildDefinitions.keySet().iterator(); while (item.hasNext()){ FpdModuleIdentification id = (FpdModuleIdentification) item.next(); usageId = new UsageIdentification(id.getModule().getName(), id.getModule().getGuid(), id.getModule().getPackage().getName(), id.getModule().getPackage().getGuid(), id.getArch(), id.getModule().getVersion(), id.getModule().getModuleType()); allModules.add( new ModulePcdInfoFromFpd( usageId, ((PcdBuildDefinitionDocument)pcdBuildDefinitions.get(id)).getPcdBuildDefinition())); } return allModules; } /** Override function: Verify the datum value according its datum size and datum type, this function maybe moved to FPD verification tools in future. @param cName The token name @param moduleName The module who use this PCD token @param datum The PCD's datum @param datumType The PCD's datum type @param maxDatumSize The max size for PCD's Datum. @return String exception strings. */ public String verifyDatum(String cName, String moduleName, String datum, Token.DATUM_TYPE datumType, int maxDatumSize) { // // In building system, datum should not be checked, the checking work // should be done by wizard tools or PCD verification tools. // return null; } /** Override function: Get dynamic information for a dynamic PCD from <DynamicPcdBuildDefinition> seciton in FPD file. This function should be implemented in GlobalData in future. @param token The token instance which has hold module's PCD information @param moduleName The name of module who will use this Dynamic PCD. @return DynamicPcdBuildDefinitions.PcdBuildData **/ public DynamicPcdBuildDefinitions.PcdBuildData getDynamicInfoFromFpd(Token token, String moduleName) throws PlatformPcdPreprocessException { int index = 0; String exceptionString = null; String dynamicPrimaryKey = null; DynamicPcdBuildDefinitions dynamicPcdBuildDefinitions = null; List<DynamicPcdBuildDefinitions.PcdBuildData> dynamicPcdBuildDataArray = null; String tokenSpaceStrRet = null; // // If FPD document is not be opened, open and initialize it. // BUGBUG: The code should be moved into GlobalData in future. // if (fpdDocInstance == null) { try { fpdDocInstance = (PlatformSurfaceAreaDocument)XmlObject.Factory.parse(new File(fpdFilePath)); } catch(IOException ioE) { throw new PlatformPcdPreprocessException("File IO error for xml file:" + fpdFilePath + "\n" + ioE.getMessage()); } catch(XmlException xmlE) { throw new PlatformPcdPreprocessException("Can't parse the FPD xml fle:" + fpdFilePath + "\n" + xmlE.getMessage()); } } dynamicPcdBuildDefinitions = fpdDocInstance.getPlatformSurfaceArea().getDynamicPcdBuildDefinitions(); if (dynamicPcdBuildDefinitions == null) { exceptionString = String.format("[FPD file error] There are no <PcdDynamicBuildDescriptions> elements in FPD file but there are Dynamic type "+ "PCD entries %s in module %s!", token.cName, moduleName); putError(exceptionString); return null; } dynamicPcdBuildDataArray = dynamicPcdBuildDefinitions.getPcdBuildDataList(); for (index = 0; index < dynamicPcdBuildDataArray.size(); index ++) { tokenSpaceStrRet = getGuidInfoFromSpd(dynamicPcdBuildDataArray.get(index).getTokenSpaceGuidCName()); if (tokenSpaceStrRet == null) { exceptionString = "Fail to get token space guid for token " + dynamicPcdBuildDataArray.get(index).getCName(); putError(exceptionString); continue; } dynamicPrimaryKey = Token.getPrimaryKeyString(dynamicPcdBuildDataArray.get(index).getCName(), tokenSpaceStrRet); if (dynamicPrimaryKey.equals(token.getPrimaryKeyString())) { return dynamicPcdBuildDataArray.get(index); } } return null; } /** Override function: get all <DynamicPcdBuildDefinition> from FPD file. @return List<DynamicPcdBuildDefinitions.PcdBuildData> All DYNAMIC PCD list in <DynamicPcdBuildDefinitions> in FPD file. @throws PlatformPcdPreprocessBuildException Failure to get dynamic information list. **/ public List<DynamicPcdBuildDefinitions.PcdBuildData> getAllDynamicPcdInfoFromFpd() throws PlatformPcdPreprocessException { DynamicPcdBuildDefinitions dynamicPcdBuildDefinitions = null; // // Open fpd document to get <DynamicPcdBuildDefinition> Section. // BUGBUG: the function should be move GlobalData in furture. // if (fpdDocInstance == null) { try { fpdDocInstance = (PlatformSurfaceAreaDocument)XmlObject.Factory.parse(new File(fpdFilePath)); } catch(IOException ioE) { throw new PlatformPcdPreprocessException("File IO error for xml file:" + fpdFilePath + "\n" + ioE.getMessage()); } catch(XmlException xmlE) { throw new PlatformPcdPreprocessException("Can't parse the FPD xml fle:" + fpdFilePath + "\n" + xmlE.getMessage()); } } dynamicPcdBuildDefinitions = fpdDocInstance.getPlatformSurfaceArea().getDynamicPcdBuildDefinitions(); if (dynamicPcdBuildDefinitions == null) { return null; } return dynamicPcdBuildDefinitions.getPcdBuildDataList(); } /** check parameter for this action. @throws PlatformPcdPreprocessBuildException Bad parameter. **/ private void checkParameter() throws PlatformPcdPreprocessBuildException { File file = null; if (fpdFilePath == null) { throw new PlatformPcdPreprocessBuildException("FPDFileName should be empty for CollectPCDAtion!"); } if (fpdFilePath.length() == 0) { throw new PlatformPcdPreprocessBuildException("FPDFileName should be empty for CollectPCDAtion!"); } file = new File(fpdFilePath); if(!file.exists()) { throw new PlatformPcdPreprocessBuildException("FPD File " + fpdFilePath + " does not exist!"); } } }
Remove unnecessary exception caching. git-svn-id: 5648d1bec6962b0a6d1d1b40eba8cf5cdb62da3d@1803 6f19259b-4bc3-4df7-8a09-765794883524
Tools/Java/Source/GenBuild/org/tianocore/build/pcd/action/PlatformPcdPreprocessActionForBuilding.java
Remove unnecessary exception caching.
<ide><path>ools/Java/Source/GenBuild/org/tianocore/build/pcd/action/PlatformPcdPreprocessActionForBuilding.java <ide> @param guidCName Guid CName string. <ide> <ide> @return String Guid information from SPD file. <del> @throws PlatformPcdPreprocessException <del> Fail to get Guid information from SPD file. <del> **/ <del> public String getGuidInfoFromSpd(String guidCName) throws PlatformPcdPreprocessException { <del> String tokenSpaceStrRet = null; <del> try { <del> tokenSpaceStrRet = GlobalData.getGuidInfoFromCname(guidCName); <del> } catch ( Exception e ) { <del> throw new PlatformPcdPreprocessException ("Failed to get Guid CName " + guidCName + " from the SPD file!"); <del> } <del> return tokenSpaceStrRet; <add> **/ <add> public String getGuidInfoFromSpd(String guidCName) { <add> return GlobalData.getGuidInfoFromCname(guidCName); <ide> } <ide> <ide> /**
Java
mit
6ef09a431d2c476fa6e10d2577a03d24bedc574c
0
markenwerk/java-commons-iterators
/* * Copyright (c) 2015, 2016 Torsten Krause, Markenwerk GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.markenwerk.commons.iterators; import java.util.Iterator; import java.util.NoSuchElementException; /** * A {@link CombinedIterator} is an {@link Iterator} that wraps around a * sequence of given {@link Iterator Iterators} and combines them into a single * {@link Iterator} by iterating over all given {@link Iterator Iterators} in * the order they were given. * * @param <Payload> * The payload type. * @author Torsten Krause (tk at markenwerk dot net) * @since 1.0.0 */ public final class CombinedIterator<Payload> implements Iterator<Payload> { private final Iterator<? extends Iterator<? extends Payload>> iterators; private Iterator<? extends Payload> currentIterator; private boolean nextPrepared; private boolean hasNext; private boolean nextCalled; /** * Creates a new {@link CombinedIterator}. * * @param iterators * The {@link Iterator Iterators} to iterate over. * * @throws IllegalArgumentException * If the given sequence of {@link Iterator Iterators} is * {@literal null}. */ public CombinedIterator(Iterator<? extends Payload>... iterators) throws IllegalArgumentException { if (null == iterators) { throw new IllegalArgumentException("The given array of iterators is null"); } this.iterators = new ArrayIterator<Iterator<? extends Payload>>(iterators); } /** * Creates a new {@link CombinedIterator}. * * @param iterators * The {@link Iterator Iterators} to iterate over. * * @throws IllegalArgumentException * If the given {@link Iterable} of {@link Iterator Iterators} * is {@literal null}. */ public CombinedIterator(Iterable<? extends Iterator<? extends Payload>> iterators) throws IllegalArgumentException { if (null == iterators) { throw new IllegalArgumentException("The given iterable of iterators is null"); } this.iterators = iterators.iterator(); } /** * Creates a new {@link CombinedIterator}. * * @param iterators * The {@link Iterator Iterators} to iterate over. * * @throws IllegalArgumentException * If the given {@link Iterator} of {@link Iterator Iterators} * is {@literal null}. */ public CombinedIterator(Iterator<? extends Iterator<? extends Payload>> iterators) throws IllegalArgumentException { if (null == iterators) { throw new IllegalArgumentException("The given iterator of iterators is null"); } this.iterators = iterators; } @Override public boolean hasNext() { prepareNext(); return hasNext; } @Override public Payload next() throws NoSuchElementException { if (!hasNext()) { throw new NoSuchElementException("This iterator has no next element"); } else { nextCalled = true; nextPrepared = false; return currentIterator.next(); } } @Override public void remove() throws IllegalStateException, UnsupportedOperationException { if (!nextCalled) { throw new IllegalStateException("Method next() hasn't been called yet"); } else { currentIterator.remove(); } } private void prepareNext() { if (!nextPrepared) { hasNext = false; if (null != currentIterator && currentIterator.hasNext()) { hasNext = true; } else { while (!hasNext && iterators.hasNext()) { currentIterator = iterators.next(); hasNext = currentIterator.hasNext(); } } nextPrepared = true; } } }
src/main/java/net/markenwerk/commons/iterators/CombinedIterator.java
/* * Copyright (c) 2015, 2016 Torsten Krause, Markenwerk GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.markenwerk.commons.iterators; import java.util.Iterator; import java.util.NoSuchElementException; /** * A {@link CombinedIterator} is an {@link Iterator} that wraps around a * sequence of given {@link Iterator Iterators} and combines them into a single * {@link Iterator} by iterating over all given {@link Iterator Iterators} in * the order they were given. * * @param <Payload> * The payload type. * @author Torsten Krause (tk at markenwerk dot net) * @since 1.0.0 */ public final class CombinedIterator<Payload> implements Iterator<Payload> { private final Iterator<? extends Iterator<? extends Payload>> iterators; private Iterator<? extends Payload> currentIterator; private boolean nextPrepared; private boolean hasNext; private boolean nextCalled; /** * Creates a new {@link CombinedIterator}. * * @param iterators * The {@link Iterator Iterators} to iterate over. * * @throws IllegalArgumentException * If the given sequence of {@link Iterator Iterators} is * {@literal null}. */ public CombinedIterator(Iterator<? extends Payload>... iterators) throws IllegalArgumentException { if (null == iterators) { throw new IllegalArgumentException("The given array of iterators is null"); } this.iterators = new ArrayIterator<Iterator<? extends Payload>>(iterators); } /** * Creates a new {@link CombinedIterator}. * * @param iterators * The {@link Iterator Iterators} to iterate over. * * @throws IllegalArgumentException * If the given {@link Iterable} of {@link Iterator Iterators} * is {@literal null}. */ public CombinedIterator(Iterable<? extends Iterator<? extends Payload>> iterators) throws IllegalArgumentException { if (null == iterators) { throw new IllegalArgumentException("The given iterable of iterators is null"); } this.iterators = iterators.iterator(); } /** * Creates a new {@link CombinedIterator}. * * @param iterators * The {@link Iterator Iterators} to iterate over. * * @throws IllegalArgumentException * If the given {@link Iterator} of {@link Iterator Iterators} * is {@literal null}. */ public CombinedIterator(Iterator<? extends Iterator<? extends Payload>> iterators) throws IllegalArgumentException { if (null == iterators) { throw new IllegalArgumentException("The given iterator iterators is null"); } this.iterators = iterators; } @Override public boolean hasNext() { prepareNext(); return hasNext; } @Override public Payload next() throws NoSuchElementException { if (!hasNext()) { throw new NoSuchElementException("This iterator has no next element"); } else { nextCalled = true; nextPrepared = false; return currentIterator.next(); } } @Override public void remove() throws IllegalStateException, UnsupportedOperationException { if (!nextCalled) { throw new IllegalStateException("Method next() hasn't been called yet"); } else { currentIterator.remove(); } } private void prepareNext() { if (!nextPrepared) { hasNext = false; if (null != currentIterator && currentIterator.hasNext()) { hasNext = true; } else { while (!hasNext && iterators.hasNext()) { currentIterator = iterators.next(); hasNext = currentIterator.hasNext(); } } nextPrepared = true; } } }
fixed typo
src/main/java/net/markenwerk/commons/iterators/CombinedIterator.java
fixed typo
<ide><path>rc/main/java/net/markenwerk/commons/iterators/CombinedIterator.java <ide> */ <ide> public CombinedIterator(Iterator<? extends Iterator<? extends Payload>> iterators) throws IllegalArgumentException { <ide> if (null == iterators) { <del> throw new IllegalArgumentException("The given iterator iterators is null"); <add> throw new IllegalArgumentException("The given iterator of iterators is null"); <ide> } <ide> this.iterators = iterators; <ide> }
Java
unlicense
5d3f02de5fb9d4fd8179ad305674bd5df59fce07
0
Samourai-Wallet/samourai-wallet-android
package com.samourai.wallet.cahoots.util; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Looper; import android.support.v4.content.FileProvider; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.client.android.Contents; import com.google.zxing.client.android.encode.QRCodeEncoder; import com.samourai.wallet.R; import com.samourai.wallet.SamouraiWallet; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.cahoots.Cahoots; import com.samourai.wallet.cahoots.STONEWALLx2; import com.samourai.wallet.cahoots.Stowaway; import com.samourai.wallet.cahoots._TransactionOutPoint; import com.samourai.wallet.cahoots._TransactionOutput; import com.samourai.wallet.cahoots.psbt.PSBT; import com.samourai.wallet.segwit.BIP84Util; import com.samourai.wallet.segwit.SegwitAddress; import com.samourai.wallet.segwit.bech32.Bech32Segwit; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.PushTx; import com.samourai.wallet.send.SendFactory; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.FormatsUtil; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Triple; import org.bitcoinj.core.Coin; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.core.TransactionOutput; import org.bouncycastle.util.encoders.Hex; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; public class CahootsUtil { private static Context context = null; private static CahootsUtil instance = null; private CahootsUtil() { ; } public static CahootsUtil getInstance(Context ctx) { context = ctx; if(instance == null) { instance = new CahootsUtil(); } return instance; } public void processCahoots(String strCahoots) { Stowaway stowaway = null; STONEWALLx2 stonewall = null; try { JSONObject obj = new JSONObject(strCahoots); Log.d("CahootsUtil", "incoming st:" + strCahoots); Log.d("CahootsUtil", "object json:" + obj.toString()); if(obj.has("cahoots") && obj.getJSONObject("cahoots").has("type")) { int type = obj.getJSONObject("cahoots").getInt("type"); switch(type) { case Cahoots.CAHOOTS_STOWAWAY: stowaway = new Stowaway(obj); Log.d("CahootsUtil", "stowaway st:" + stowaway.toJSON().toString()); break; case Cahoots.CAHOOTS_STONEWALLx2: stonewall = new STONEWALLx2(obj); Log.d("CahootsUtil", "stonewall st:" + stonewall.toJSON().toString()); break; default: Toast.makeText(context, R.string.unrecognized_cahoots, Toast.LENGTH_SHORT).show(); return; } } else { Toast.makeText(context, R.string.not_cahoots, Toast.LENGTH_SHORT).show(); return; } } catch(JSONException je) { Toast.makeText(context, R.string.cannot_process_cahoots, Toast.LENGTH_SHORT).show(); return; } if(stowaway != null) { int step = stowaway.getStep(); try { switch(step) { case 0: Log.d("CahootsUtil", "calling doStowaway1"); doStowaway1(stowaway); break; case 1: doStowaway2(stowaway); break; case 2: doStowaway3(stowaway); break; case 3: doStowaway4(stowaway); break; default: Toast.makeText(context, R.string.unrecognized_step, Toast.LENGTH_SHORT).show(); break; } } catch(Exception e) { Toast.makeText(context, R.string.cannot_process_stonewall, Toast.LENGTH_SHORT).show(); Log.d("CahootsUtil", e.getMessage()); e.printStackTrace(); } return; } else if(stonewall != null) { int step = stonewall.getStep(); try { switch(step) { case 0: doSTONEWALLx2_1(stonewall); break; case 1: doSTONEWALLx2_2(stonewall); break; case 2: doSTONEWALLx2_3(stonewall); break; case 3: doSTONEWALLx2_4(stonewall); break; default: Toast.makeText(context, R.string.unrecognized_step, Toast.LENGTH_SHORT).show(); break; } } catch(Exception e) { Toast.makeText(context, R.string.cannot_process_stowaway, Toast.LENGTH_SHORT).show(); Log.d("CahootsUtil", e.getMessage()); e.printStackTrace(); } return; } else { Toast.makeText(context, "error processing #Cahoots", Toast.LENGTH_SHORT).show(); } } private void doCahoots(final String strCahoots) { Cahoots cahoots = null; Transaction transaction = null; int step = 0; try { JSONObject jsonObject = new JSONObject(strCahoots); if(jsonObject != null && jsonObject.has("cahoots") && jsonObject.getJSONObject("cahoots").has("step")) { step = jsonObject.getJSONObject("cahoots").getInt("step"); if(step == 4 || step == 3) { cahoots = new Stowaway(jsonObject); transaction = cahoots.getPSBT().getTransaction(); } } } catch(JSONException je) { Toast.makeText(context, je.getMessage(), Toast.LENGTH_SHORT).show(); } final int _step = step; final Transaction _transaction = transaction; final int QR_ALPHANUM_CHAR_LIMIT = 4296; // tx max size in bytes == 2148 TextView showTx = new TextView(context); showTx.setText(step != 4 ? strCahoots : Hex.toHexString(transaction.bitcoinSerialize())); showTx.setTextIsSelectable(true); showTx.setPadding(40, 10, 40, 10); showTx.setTextSize(18.0f); LinearLayout hexLayout = new LinearLayout(context); hexLayout.setOrientation(LinearLayout.VERTICAL); hexLayout.addView(showTx); String title = context.getString(R.string.cahoots); title += ", "; title += (_step + 1); title += "/5"; AlertDialog.Builder dlg = new AlertDialog.Builder(context) .setTitle(title) .setView(hexLayout) .setCancelable(true) .setPositiveButton(R.string.copy_to_clipboard, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { android.content.ClipboardManager clipboard = (android.content.ClipboardManager)context.getSystemService(android.content.Context.CLIPBOARD_SERVICE); android.content.ClipData clip = null; clip = android.content.ClipData.newPlainText("Cahoots", _step != 4 ? strCahoots : Hex.toHexString(_transaction.bitcoinSerialize())); clipboard.setPrimaryClip(clip); Toast.makeText(context, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show(); } }) .setNegativeButton(R.string.show_qr, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if(strCahoots.length() <= QR_ALPHANUM_CHAR_LIMIT) { final ImageView ivQR = new ImageView(context); Display display = ((Activity)context).getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int imgWidth = Math.max(size.x - 240, 150); Bitmap bitmap = null; QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(strCahoots, null, Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), imgWidth); try { bitmap = qrCodeEncoder.encodeAsBitmap(); } catch (WriterException e) { e.printStackTrace(); } ivQR.setImageBitmap(bitmap); LinearLayout qrLayout = new LinearLayout(context); qrLayout.setOrientation(LinearLayout.VERTICAL); qrLayout.addView(ivQR); new AlertDialog.Builder(context) .setTitle(R.string.cahoots) .setView(qrLayout) .setCancelable(false) .setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }) .setNegativeButton(R.string.share_qr, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String strFileName = AppUtil.getInstance(context).getReceiveQRFilename(); File file = new File(strFileName); if(!file.exists()) { try { file.createNewFile(); } catch(Exception e) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show(); } } file.setReadable(true, false); FileOutputStream fos = null; try { fos = new FileOutputStream(file); } catch(FileNotFoundException fnfe) { ; } if(file != null && fos != null) { Bitmap bitmap = ((BitmapDrawable)ivQR.getDrawable()).getBitmap(); bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos); try { fos.close(); } catch(IOException ioe) { ; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/png"); if (android.os.Build.VERSION.SDK_INT >= 24) { //From API 24 sending FIle on intent ,require custom file provider intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile( context, context.getApplicationContext() .getPackageName() + ".provider", file)); } else { intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); } context.startActivity(Intent.createChooser(intent, context.getText(R.string.send_tx))); } } }).show(); } else { Toast.makeText(context, R.string.tx_too_large_qr, Toast.LENGTH_SHORT).show(); } } }); if(_step == 4) { dlg.setPositiveButton(R.string.broadcast, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); PushTx.getInstance(context).pushTx(Hex.toHexString(_transaction.bitcoinSerialize())); Looper.loop(); } }).start(); } }); dlg.setNeutralButton(R.string.show_tx, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String tx = ""; if(_transaction != null) { tx = _transaction.toString(); } TextView showText = new TextView(context); showText.setText(tx); showText.setTextIsSelectable(true); showText.setPadding(40, 10, 40, 10); showText.setTextSize(18.0f); new AlertDialog.Builder(context) .setTitle(R.string.app_name) .setView(showText) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }).show(); } }); } else if(_step == 3) { dlg.setNeutralButton(R.string.show_tx, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String tx = ""; if(_transaction != null) { tx = _transaction.toString(); } TextView showText = new TextView(context); showText.setText(tx); showText.setTextIsSelectable(true); showText.setPadding(40, 10, 40, 10); showText.setTextSize(18.0f); new AlertDialog.Builder(context) .setTitle(R.string.app_name) .setView(showText) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }).show(); } }); } else { ; } if(!((Activity)context).isFinishing()) { dlg.show(); } } public void doPSBT(final String strPSBT) { String msg = null; PSBT psbt = new PSBT(strPSBT, SamouraiWallet.getInstance().getCurrentNetworkParams()); try { psbt.read(); msg = psbt.dump(); } catch(Exception e) { msg = e.getMessage(); } final EditText edPSBT = new EditText(context); edPSBT.setSingleLine(false); edPSBT.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE); edPSBT.setLines(10); edPSBT.setHint(R.string.PSBT); edPSBT.setGravity(Gravity.START); TextWatcher textWatcher = new TextWatcher() { public void afterTextChanged(Editable s) { edPSBT.setSelection(0); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { ; } public void onTextChanged(CharSequence s, int start, int before, int count) { ; } }; edPSBT.addTextChangedListener(textWatcher); edPSBT.setText(msg); AlertDialog.Builder dlg = new AlertDialog.Builder(context) .setTitle(R.string.app_name) .setMessage(R.string.PSBT) .setView(edPSBT) .setCancelable(true) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!((Activity)context).isFinishing()) { dlg.show(); } } public void doStowaway0(long spendAmount) { // Bob -> Alice, spendAmount in sats NetworkParameters params = SamouraiWallet.getInstance().getCurrentNetworkParams(); // // // step0: B sends spend amount to A, creates step0 // // Stowaway stowaway0 = new Stowaway(spendAmount, params); System.out.println(stowaway0.toJSON().toString()); doCahoots(stowaway0.toJSON().toString()); } private void doStowaway1(Stowaway stowaway0) throws Exception { List<UTXO> utxos = getCahootsUTXO(); // sort in descending order by value Collections.sort(utxos, new UTXO.UTXOComparator()); Log.d("CahootsUtil", "BIP84 utxos:" + utxos.size()); List<UTXO> selectedUTXO = new ArrayList<UTXO>(); long totalContributedAmount = 0L; for(UTXO utxo : utxos) { selectedUTXO.add(utxo); totalContributedAmount += utxo.getValue(); Log.d("CahootsUtil", "BIP84 selected utxo:" + utxo.getValue()); if(totalContributedAmount > stowaway0.getSpendAmount() + SamouraiWallet.bDust.longValue()) { break; } } if(!(totalContributedAmount > stowaway0.getSpendAmount() + SamouraiWallet.bDust.longValue())) { Toast.makeText(context, R.string.cannot_compose_cahoots, Toast.LENGTH_SHORT).show(); return; } Log.d("CahootsUtil", "BIP84 selected utxos:" + selectedUTXO.size()); NetworkParameters params = stowaway0.getParams(); // // // step1: A utxos -> B (take largest that cover amount) // A provides 5750000 // // String zpub = BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr(); HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>> inputsA = new HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>>(); // inputsA.put(outpoint_A0, Triple.of(Hex.decode("0221b719bc26fb49971c7dd328a6c7e4d17dfbf4e2217bee33a65c53ed3daf041e"), FormatsUtil.getInstance().getFingerprintFromXPUB("vpub5Z3hqXewnCbxnMsWygxN8AyjNVJbFeV2VCdDKpTFazdoC29qK4Y5DSQ1aaAPBrsBZ1TzN5va6xGy4eWa9uAqh2AwifuA1eofkedh3eUgF6b"), "M/0/4")); // inputsA.put(outpoint_A1, Triple.of(Hex.decode("020ab261e1a3cf986ecb3cd02299de36295e804fd799934dc5c99dde0d25e71b93"), FormatsUtil.getInstance().getFingerprintFromXPUB("vpub5Z3hqXewnCbxnMsWygxN8AyjNVJbFeV2VCdDKpTFazdoC29qK4Y5DSQ1aaAPBrsBZ1TzN5va6xGy4eWa9uAqh2AwifuA1eofkedh3eUgF6b"), "M/0/2")); for(UTXO utxo : selectedUTXO) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { _TransactionOutPoint _outpoint = new _TransactionOutPoint(outpoint); ECKey eckey = SendFactory.getPrivKey(_outpoint.getAddress()); String path = APIFactory.getInstance(context).getUnspentPaths().get(_outpoint.getAddress()); inputsA.put(_outpoint, Triple.of(eckey.getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(zpub), path)); } } // destination output int idx = BIP84Util.getInstance(context).getWallet().getAccount(0).getReceive().getAddrIdx(); SegwitAddress segwitAddress = BIP84Util.getInstance(context).getAddressAt(0, idx); HashMap<_TransactionOutput, Triple<byte[], byte[], String>> outputsA = new HashMap<_TransactionOutput, Triple<byte[], byte[], String>>(); // byte[] scriptPubKey_A = getScriptPubKey("tb1qewwlc2dksuez3zauf38d82m7uqd4ewkf2avdl8", params); Pair<Byte, byte[]> pair = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", segwitAddress.getBech32AsString()); byte[] scriptPubKey_A = Bech32Segwit.getScriptPubkey(pair.getLeft(), pair.getRight()); _TransactionOutput output_A0 = new _TransactionOutput(params, null, Coin.valueOf(stowaway0.getSpendAmount()), scriptPubKey_A); outputsA.put(output_A0, Triple.of(segwitAddress.getECKey().getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()), "M/0/" + idx)); Stowaway stowaway1 = new Stowaway(stowaway0); stowaway1.inc(inputsA, outputsA, null); doCahoots(stowaway1.toJSON().toString()); } private void doStowaway2(Stowaway stowaway1) throws Exception { Transaction transaction = stowaway1.getTransaction(); Log.d("CahootsUtil", "step2 tx:" + org.spongycastle.util.encoders.Hex.toHexString(transaction.bitcoinSerialize())); // Log.d("CahootsUtil", "input value:" + transaction.getInputs().get(0).getValue().longValue()); int nbIncomingInputs = transaction.getInputs().size(); List<UTXO> utxos = getCahootsUTXO(); // sort in ascending order by value Collections.sort(utxos, new UTXO.UTXOComparator()); Collections.reverse(utxos); Log.d("CahootsUtil", "BIP84 utxos:" + utxos.size()); List<UTXO> selectedUTXO = new ArrayList<UTXO>(); int nbTotalSelectedOutPoints = 0; long totalSelectedAmount = 0L; for(UTXO utxo : utxos) { selectedUTXO.add(utxo); totalSelectedAmount += utxo.getValue(); Log.d("BIP84 selected utxo:", "" + utxo.getValue()); nbTotalSelectedOutPoints += utxo.getOutpoints().size(); if(totalSelectedAmount > FeeUtil.getInstance().estimatedFeeSegwit(0, 0, nbTotalSelectedOutPoints + nbIncomingInputs, 2).longValue() + stowaway1.getSpendAmount() + SamouraiWallet.bDust.longValue()) { // discard "extra" utxo, if any List<UTXO> _selectedUTXO = new ArrayList<UTXO>(); Collections.reverse(selectedUTXO); int _nbTotalSelectedOutPoints = 0; long _totalSelectedAmount = 0L; for(UTXO utxoSel : selectedUTXO) { _selectedUTXO.add(utxoSel); _totalSelectedAmount += utxoSel.getValue(); Log.d("CahootsUtil", "BIP84 post selected utxo:" + utxoSel.getValue()); _nbTotalSelectedOutPoints += utxoSel.getOutpoints().size(); if(_totalSelectedAmount > FeeUtil.getInstance().estimatedFeeSegwit(0, 0, _nbTotalSelectedOutPoints + nbIncomingInputs, 2).longValue() + stowaway1.getSpendAmount() + SamouraiWallet.bDust.longValue()) { selectedUTXO.clear(); selectedUTXO.addAll(_selectedUTXO); totalSelectedAmount = _totalSelectedAmount; nbTotalSelectedOutPoints = _nbTotalSelectedOutPoints; break; } } break; } } if(!(totalSelectedAmount > FeeUtil.getInstance().estimatedFeeSegwit(0, 0, nbTotalSelectedOutPoints + nbIncomingInputs, 2).longValue() + stowaway1.getSpendAmount() + SamouraiWallet.bDust.longValue())) { Toast.makeText(context, R.string.cannot_compose_cahoots, Toast.LENGTH_SHORT).show(); return; } Log.d("CahootsUtil", "BIP84 selected utxos:" + selectedUTXO.size()); long fee = FeeUtil.getInstance().estimatedFeeSegwit(0, 0, nbTotalSelectedOutPoints + nbIncomingInputs, 2).longValue(); Log.d("CahootsUtil", "fee:" + fee); NetworkParameters params = stowaway1.getParams(); // // // step2: B verif, utxos -> A (take smallest that cover amount) // B provides 1000000, 1500000 (250000 change, A input larger) // // String zpub = BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr(); HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>> inputsB = new HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>>(); for(UTXO utxo : selectedUTXO) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { _TransactionOutPoint _outpoint = new _TransactionOutPoint(outpoint); ECKey eckey = SendFactory.getPrivKey(_outpoint.getAddress()); String path = APIFactory.getInstance(context).getUnspentPaths().get(_outpoint.getAddress()); inputsB.put(_outpoint, Triple.of(eckey.getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(zpub), path)); } } Log.d("CahootsUtil", "inputsB:" + inputsB.size()); // change output int idx = BIP84Util.getInstance(context).getWallet().getAccount(0).getChange().getAddrIdx(); SegwitAddress segwitAddress = BIP84Util.getInstance(context).getAddressAt(1, idx); HashMap<_TransactionOutput, Triple<byte[], byte[], String>> outputsB = new HashMap<_TransactionOutput, Triple<byte[], byte[], String>>(); Pair<Byte, byte[]> pair = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", segwitAddress.getBech32AsString()); byte[] scriptPubKey_B = Bech32Segwit.getScriptPubkey(pair.getLeft(), pair.getRight()); _TransactionOutput output_B0 = new _TransactionOutput(params, null, Coin.valueOf((totalSelectedAmount - stowaway1.getSpendAmount()) - fee), scriptPubKey_B); outputsB.put(output_B0, Triple.of(segwitAddress.getECKey().getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()), "M/1/" + idx)); Log.d("CahootsUtil", "outputsB:" + outputsB.size()); Stowaway stowaway2 = new Stowaway(stowaway1); stowaway2.inc(inputsB, outputsB, null); System.out.println("step 2:" + stowaway2.toJSON().toString()); doCahoots(stowaway2.toJSON().toString()); } private void doStowaway3(Stowaway stowaway2) throws Exception { HashMap<String,String> utxo2Address = new HashMap<String,String>(); List<UTXO> utxos = APIFactory.getInstance(context).getUtxos(true); for(UTXO utxo : utxos) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { utxo2Address.put(outpoint.getTxHash().toString() + "-" + outpoint.getTxOutputN(), outpoint.getAddress()); Log.d("CahootsUtil", "outpoint address:" + outpoint.getTxHash().toString() + "-" + outpoint.getTxOutputN() + "," + outpoint.getAddress()); } } Transaction transaction = stowaway2.getPSBT().getTransaction(); HashMap<String,ECKey> keyBag_A = new HashMap<String,ECKey>(); for(TransactionInput input : transaction.getInputs()) { TransactionOutPoint outpoint = input.getOutpoint(); String key = outpoint.getHash().toString() + "-" + outpoint.getIndex(); if(utxo2Address.containsKey(key)) { String address = utxo2Address.get(key); ECKey eckey = SendFactory.getPrivKey(address); keyBag_A.put(outpoint.toString(), eckey); } } // // // step3: A verif, BIP69, sig // // /* HashMap<String,ECKey> keyBag_A = new HashMap<String,ECKey>(); keyBag_A.put(outpoint_A0.toString(), ecKey_A0); keyBag_A.put(outpoint_A1.toString(), ecKey_A1); */ Stowaway stowaway3 = new Stowaway(stowaway2); stowaway3.inc(null, null, keyBag_A); System.out.println("step 3:" + stowaway3.toJSON().toString()); doCahoots(stowaway3.toJSON().toString()); } private void doStowaway4(Stowaway stowaway3) throws Exception { HashMap<String,String> utxo2Address = new HashMap<String,String>(); List<UTXO> utxos = APIFactory.getInstance(context).getUtxos(true); for(UTXO utxo : utxos) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { utxo2Address.put(outpoint.getTxHash().toString() + "-" + outpoint.getTxOutputN(), outpoint.getAddress()); Log.d("CahootsUtil", "outpoint address:" + outpoint.getTxHash().toString() + "-" + outpoint.getTxOutputN() + "," + outpoint.getAddress()); } } Transaction transaction = stowaway3.getPSBT().getTransaction(); HashMap<String,ECKey> keyBag_B = new HashMap<String,ECKey>(); for(TransactionInput input : transaction.getInputs()) { TransactionOutPoint outpoint = input.getOutpoint(); String key = outpoint.getHash().toString() + "-" + outpoint.getIndex(); if(utxo2Address.containsKey(key)) { String address = utxo2Address.get(key); ECKey eckey = SendFactory.getPrivKey(address); keyBag_B.put(outpoint.toString(), eckey); } } // // // step4: B verif, sig, broadcast // // /* HashMap<String,ECKey> keyBag_B = new HashMap<String,ECKey>(); keyBag_B.put(outpoint_B0.toString(), ecKey_B0); keyBag_B.put(outpoint_B1.toString(), ecKey_B1); */ Stowaway stowaway4 = new Stowaway(stowaway3); stowaway4.inc(null, null, keyBag_B); System.out.println("step 4:" + stowaway4.toJSON().toString()); System.out.println("step 4 psbt:" + stowaway4.getPSBT().toString()); System.out.println("step 4 tx:" + stowaway4.getTransaction().toString()); System.out.println("step 4 tx hex:" + Hex.toHexString(stowaway4.getTransaction().bitcoinSerialize())); // Stowaway s = new Stowaway(stowaway4.toJSON()); // System.out.println(s.toJSON().toString()); // broadcast ??? doCahoots(stowaway4.toJSON().toString()); } public void doSTONEWALLx2_0(long spendAmount, String address) { // Bob -> Alice, spendAmount in sats NetworkParameters params = SamouraiWallet.getInstance().getCurrentNetworkParams(); // // // step0: B sends spend amount to A, creates step0 // // STONEWALLx2 stonewall0 = new STONEWALLx2(spendAmount, address, params); System.out.println(stonewall0.toJSON().toString()); doCahoots(stonewall0.toJSON().toString()); } private void doSTONEWALLx2_1(STONEWALLx2 stonewall0) throws Exception { List<UTXO> utxos = getCahootsUTXO(); Collections.shuffle(utxos); Log.d("CahootsUtil", "BIP84 utxos:" + utxos.size()); List<String> seenTxs = new ArrayList<String>(); List<UTXO> selectedUTXO = new ArrayList<UTXO>(); long totalContributedAmount = 0L; for(UTXO utxo : utxos) { UTXO _utxo = new UTXO(); for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { if(!seenTxs.contains(outpoint.getTxHash().toString())) { _utxo.getOutpoints().add(outpoint); seenTxs.add(outpoint.getTxHash().toString()); } } if(_utxo.getOutpoints().size() > 0) { selectedUTXO.add(_utxo); totalContributedAmount += _utxo.getValue(); Log.d("CahootsUtil", "BIP84 selected utxo:" + _utxo.getValue()); } if(totalContributedAmount > stonewall0.getSpendAmount() + SamouraiWallet.bDust.longValue()) { break; } } if(!(totalContributedAmount > stonewall0.getSpendAmount() + SamouraiWallet.bDust.longValue())) { Toast.makeText(context, R.string.cannot_compose_cahoots, Toast.LENGTH_SHORT).show(); return; } Log.d("CahootsUtil", "BIP84 selected utxos:" + selectedUTXO.size()); NetworkParameters params = stonewall0.getParams(); // // // step1: A utxos -> B (take largest that cover amount) // A provides 5750000 // // String zpub = BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr(); HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>> inputsA = new HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>>(); for(UTXO utxo : selectedUTXO) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { _TransactionOutPoint _outpoint = new _TransactionOutPoint(outpoint); ECKey eckey = SendFactory.getPrivKey(_outpoint.getAddress()); String path = APIFactory.getInstance(context).getUnspentPaths().get(_outpoint.getAddress()); inputsA.put(_outpoint, Triple.of(eckey.getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(zpub), path)); } } // contributor mix output int idx = BIP84Util.getInstance(context).getWallet().getAccount(0).getReceive().getAddrIdx(); SegwitAddress segwitAddress0 = BIP84Util.getInstance(context).getAddressAt(0, idx); if(segwitAddress0.getBech32AsString().equalsIgnoreCase(stonewall0.getDestination())) { segwitAddress0 = BIP84Util.getInstance(context).getAddressAt(0, idx + 1); } HashMap<_TransactionOutput, Triple<byte[], byte[], String>> outputsA = new HashMap<_TransactionOutput, Triple<byte[], byte[], String>>(); Pair<Byte, byte[]> pair0 = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", segwitAddress0.getBech32AsString()); byte[] scriptPubKey_A0 = Bech32Segwit.getScriptPubkey(pair0.getLeft(), pair0.getRight()); _TransactionOutput output_A0 = new _TransactionOutput(params, null, Coin.valueOf(stonewall0.getSpendAmount()), scriptPubKey_A0); outputsA.put(output_A0, Triple.of(segwitAddress0.getECKey().getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()), "M/0/" + idx)); // contributor change output idx = BIP84Util.getInstance(context).getWallet().getAccount(0).getChange().getAddrIdx(); SegwitAddress segwitAddress1 = BIP84Util.getInstance(context).getAddressAt(1, idx); Pair<Byte, byte[]> pair1 = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", segwitAddress1.getBech32AsString()); byte[] scriptPubKey_A1 = Bech32Segwit.getScriptPubkey(pair1.getLeft(), pair1.getRight()); _TransactionOutput output_A1 = new _TransactionOutput(params, null, Coin.valueOf(totalContributedAmount - stonewall0.getSpendAmount()), scriptPubKey_A1); outputsA.put(output_A1, Triple.of(segwitAddress1.getECKey().getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()), "M/1/" + idx)); STONEWALLx2 stonewall1 = new STONEWALLx2(stonewall0); stonewall1.inc(inputsA, outputsA, null); doCahoots(stonewall1.toJSON().toString()); } private void doSTONEWALLx2_2(STONEWALLx2 stonewall1) throws Exception { Transaction transaction = stonewall1.getTransaction(); Log.d("CahootsUtil", "step2 tx:" + org.spongycastle.util.encoders.Hex.toHexString(transaction.bitcoinSerialize())); // Log.d("CahootsUtil", "input value:" + transaction.getInputs().get(0).getValue().longValue()); int nbIncomingInputs = transaction.getInputs().size(); List<UTXO> utxos = getCahootsUTXO(); Collections.shuffle(utxos); Log.d("CahootsUtil", "BIP84 utxos:" + utxos.size()); List<String> seenTxs = new ArrayList<String>(); for(TransactionInput input : transaction.getInputs()) { if(!seenTxs.contains(input.getOutpoint().getHash().toString())) { seenTxs.add(input.getOutpoint().getHash().toString()); } } List<UTXO> selectedUTXO = new ArrayList<UTXO>(); int nbTotalSelectedOutPoints = 0; long totalSelectedAmount = 0L; for(UTXO utxo : utxos) { UTXO _utxo = new UTXO(); for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { if(!seenTxs.contains(outpoint.getTxHash().toString())) { _utxo.getOutpoints().add(outpoint); seenTxs.add(outpoint.getTxHash().toString()); } } if(_utxo.getOutpoints().size() > 0) { selectedUTXO.add(_utxo); totalSelectedAmount += _utxo.getValue(); nbTotalSelectedOutPoints += _utxo.getOutpoints().size(); Log.d("CahootsUtil", "BIP84 selected utxo:" + _utxo.getValue()); } if(totalSelectedAmount > FeeUtil.getInstance().estimatedFeeSegwit(0, 0, nbTotalSelectedOutPoints + nbIncomingInputs, 4).longValue() + stonewall1.getSpendAmount() + SamouraiWallet.bDust.longValue()) { break; } } if(!(totalSelectedAmount > FeeUtil.getInstance().estimatedFeeSegwit(0, 0, nbTotalSelectedOutPoints + nbIncomingInputs, 4).longValue() + stonewall1.getSpendAmount() + SamouraiWallet.bDust.longValue())) { Toast.makeText(context, R.string.cannot_compose_cahoots, Toast.LENGTH_SHORT).show(); return; } Log.d("CahootsUtil", "BIP84 selected utxos:" + selectedUTXO.size()); long fee = FeeUtil.getInstance().estimatedFeeSegwit(0, 0, nbTotalSelectedOutPoints + nbIncomingInputs, 4).longValue(); Log.d("CahootsUtil", "fee:" + fee); NetworkParameters params = stonewall1.getParams(); // // // step2: B verif, utxos -> A (take smallest that cover amount) // B provides 1000000, 1500000 (250000 change, A input larger) // // String zpub = BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr(); HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>> inputsB = new HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>>(); for(UTXO utxo : selectedUTXO) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { _TransactionOutPoint _outpoint = new _TransactionOutPoint(outpoint); ECKey eckey = SendFactory.getPrivKey(_outpoint.getAddress()); String path = APIFactory.getInstance(context).getUnspentPaths().get(_outpoint.getAddress()); inputsB.put(_outpoint, Triple.of(eckey.getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(zpub), path)); } } // spender change output int idx = BIP84Util.getInstance(context).getWallet().getAccount(0).getChange().getAddrIdx(); SegwitAddress segwitAddress = BIP84Util.getInstance(context).getAddressAt(1, idx); HashMap<_TransactionOutput, Triple<byte[], byte[], String>> outputsB = new HashMap<_TransactionOutput, Triple<byte[], byte[], String>>(); Pair<Byte, byte[]> pair0 = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", segwitAddress.getBech32AsString()); byte[] scriptPubKey_B0 = Bech32Segwit.getScriptPubkey(pair0.getLeft(), pair0.getRight()); _TransactionOutput output_B0 = new _TransactionOutput(params, null, Coin.valueOf((totalSelectedAmount - stonewall1.getSpendAmount()) - fee), scriptPubKey_B0); outputsB.put(output_B0, Triple.of(segwitAddress.getECKey().getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()), "M/1/" + idx)); STONEWALLx2 stonewall2 = new STONEWALLx2(stonewall1); stonewall2.inc(inputsB, outputsB, null); System.out.println("step 2:" + stonewall2.toJSON().toString()); doCahoots(stonewall2.toJSON().toString()); } private void doSTONEWALLx2_3(STONEWALLx2 stonewall2) throws Exception { HashMap<String,String> utxo2Address = new HashMap<String,String>(); List<UTXO> utxos = APIFactory.getInstance(context).getUtxos(true); for(UTXO utxo : utxos) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { utxo2Address.put(outpoint.getTxHash().toString() + "-" + outpoint.getTxOutputN(), outpoint.getAddress()); } } // Transaction transaction = stonewall2.getPSBT().getTransaction(); Transaction transaction = stonewall2.getTransaction(); HashMap<String,ECKey> keyBag_A = new HashMap<String,ECKey>(); for(TransactionInput input : transaction.getInputs()) { TransactionOutPoint outpoint = input.getOutpoint(); String key = outpoint.getHash().toString() + "-" + outpoint.getIndex(); if(utxo2Address.containsKey(key)) { String address = utxo2Address.get(key); ECKey eckey = SendFactory.getPrivKey(address); keyBag_A.put(outpoint.toString(), eckey); } } // // // step3: A verif, BIP69, sig // // /* HashMap<String,ECKey> keyBag_A = new HashMap<String,ECKey>(); keyBag_A.put(outpoint_A0.toString(), ecKey_A0); keyBag_A.put(outpoint_A1.toString(), ecKey_A1); */ STONEWALLx2 stonewall3 = new STONEWALLx2(stonewall2); stonewall3.inc(null, null, keyBag_A); System.out.println("step 3:" + stonewall3.toJSON().toString()); doCahoots(stonewall3.toJSON().toString()); } private void doSTONEWALLx2_4(STONEWALLx2 stonewall3) throws Exception { HashMap<String,String> utxo2Address = new HashMap<String,String>(); List<UTXO> utxos = APIFactory.getInstance(context).getUtxos(true); for(UTXO utxo : utxos) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { utxo2Address.put(outpoint.getTxHash().toString() + "-" + outpoint.getTxOutputN(), outpoint.getAddress()); } } // Transaction transaction = stonewall3.getPSBT().getTransaction(); Transaction transaction = stonewall3.getTransaction(); HashMap<String,ECKey> keyBag_B = new HashMap<String,ECKey>(); for(TransactionInput input : transaction.getInputs()) { TransactionOutPoint outpoint = input.getOutpoint(); String key = outpoint.getHash().toString() + "-" + outpoint.getIndex(); if(utxo2Address.containsKey(key)) { String address = utxo2Address.get(key); ECKey eckey = SendFactory.getPrivKey(address); keyBag_B.put(outpoint.toString(), eckey); } } // // // step4: B verif, sig, broadcast // // /* HashMap<String,ECKey> keyBag_B = new HashMap<String,ECKey>(); keyBag_B.put(outpoint_B0.toString(), ecKey_B0); keyBag_B.put(outpoint_B1.toString(), ecKey_B1); */ STONEWALLx2 stonewall4 = new STONEWALLx2(stonewall3); stonewall4.inc(null, null, keyBag_B); System.out.println("step 4:" + stonewall4.toJSON().toString()); System.out.println("step 4 psbt:" + stonewall4.getPSBT().toString()); System.out.println("step 4 tx:" + stonewall4.getTransaction().toString()); System.out.println("step 4 tx hex:" + Hex.toHexString(stonewall4.getTransaction().bitcoinSerialize())); // Stowaway s = new Stowaway(stowaway4.toJSON()); // System.out.println(s.toJSON().toString()); // broadcast ??? doCahoots(stonewall4.toJSON().toString()); } private List<UTXO> getCahootsUTXO() { List<UTXO> ret = new ArrayList<UTXO>(); List<UTXO> _utxos = APIFactory.getInstance(context).getUtxos(true); for(UTXO utxo : _utxos) { String script = Hex.toHexString(utxo.getOutpoints().get(0).getScriptBytes()); if(script.startsWith("0014") && APIFactory.getInstance(context).getUnspentPaths().get(utxo.getOutpoints().get(0).getAddress()) != null) { ret.add(utxo); } } return ret; } public long getCahootsValue() { long ret = 0L; List<UTXO> _utxos = getCahootsUTXO(); for(UTXO utxo : _utxos) { ret += utxo.getValue(); } return ret; } }
app/src/main/java/com/samourai/wallet/cahoots/util/CahootsUtil.java
package com.samourai.wallet.cahoots.util; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Looper; import android.support.v4.content.FileProvider; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.client.android.Contents; import com.google.zxing.client.android.encode.QRCodeEncoder; import com.samourai.wallet.R; import com.samourai.wallet.SamouraiWallet; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.cahoots.Cahoots; import com.samourai.wallet.cahoots.STONEWALLx2; import com.samourai.wallet.cahoots.Stowaway; import com.samourai.wallet.cahoots._TransactionOutPoint; import com.samourai.wallet.cahoots._TransactionOutput; import com.samourai.wallet.cahoots.psbt.PSBT; import com.samourai.wallet.segwit.BIP84Util; import com.samourai.wallet.segwit.SegwitAddress; import com.samourai.wallet.segwit.bech32.Bech32Segwit; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.PushTx; import com.samourai.wallet.send.SendFactory; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.FormatsUtil; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Triple; import org.bitcoinj.core.Coin; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.core.TransactionOutput; import org.bouncycastle.util.encoders.Hex; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; public class CahootsUtil { private static Context context = null; private static CahootsUtil instance = null; private CahootsUtil() { ; } public static CahootsUtil getInstance(Context ctx) { context = ctx; if(instance == null) { instance = new CahootsUtil(); } return instance; } public void processCahoots(String strCahoots) { Stowaway stowaway = null; STONEWALLx2 stonewall = null; try { JSONObject obj = new JSONObject(strCahoots); Log.d("CahootsUtil", "incoming st:" + strCahoots); Log.d("CahootsUtil", "object json:" + obj.toString()); if(obj.has("cahoots") && obj.getJSONObject("cahoots").has("type")) { int type = obj.getJSONObject("cahoots").getInt("type"); switch(type) { case Cahoots.CAHOOTS_STOWAWAY: stowaway = new Stowaway(obj); Log.d("CahootsUtil", "stowaway st:" + stowaway.toJSON().toString()); break; case Cahoots.CAHOOTS_STONEWALLx2: stonewall = new STONEWALLx2(obj); Log.d("CahootsUtil", "stonewall st:" + stonewall.toJSON().toString()); break; default: Toast.makeText(context, R.string.unrecognized_cahoots, Toast.LENGTH_SHORT).show(); return; } } else { Toast.makeText(context, R.string.not_cahoots, Toast.LENGTH_SHORT).show(); return; } } catch(JSONException je) { Toast.makeText(context, R.string.cannot_process_cahoots, Toast.LENGTH_SHORT).show(); return; } if(stowaway != null) { int step = stowaway.getStep(); try { switch(step) { case 0: Log.d("CahootsUtil", "calling doStowaway1"); doStowaway1(stowaway); break; case 1: doStowaway2(stowaway); break; case 2: doStowaway3(stowaway); break; case 3: doStowaway4(stowaway); break; default: Toast.makeText(context, R.string.unrecognized_step, Toast.LENGTH_SHORT).show(); break; } } catch(Exception e) { Toast.makeText(context, R.string.cannot_process_stonewall, Toast.LENGTH_SHORT).show(); Log.d("CahootsUtil", e.getMessage()); e.printStackTrace(); } return; } else if(stonewall != null) { int step = stonewall.getStep(); try { switch(step) { case 0: doSTONEWALLx2_1(stonewall); break; case 1: doSTONEWALLx2_2(stonewall); break; case 2: doSTONEWALLx2_3(stonewall); break; case 3: doSTONEWALLx2_4(stonewall); break; default: Toast.makeText(context, R.string.unrecognized_step, Toast.LENGTH_SHORT).show(); break; } } catch(Exception e) { Toast.makeText(context, R.string.cannot_process_stowaway, Toast.LENGTH_SHORT).show(); Log.d("CahootsUtil", e.getMessage()); e.printStackTrace(); } return; } else { Toast.makeText(context, "error processing #Cahoots", Toast.LENGTH_SHORT).show(); } } private void doCahoots(final String strCahoots) { Cahoots cahoots = null; Transaction transaction = null; int step = 0; try { JSONObject jsonObject = new JSONObject(strCahoots); if(jsonObject != null && jsonObject.has("cahoots") && jsonObject.getJSONObject("cahoots").has("step")) { step = jsonObject.getJSONObject("cahoots").getInt("step"); if(step == 4 || step == 3) { cahoots = new Stowaway(jsonObject); transaction = cahoots.getPSBT().getTransaction(); } } } catch(JSONException je) { Toast.makeText(context, je.getMessage(), Toast.LENGTH_SHORT).show(); } final int _step = step; final Transaction _transaction = transaction; final int QR_ALPHANUM_CHAR_LIMIT = 4296; // tx max size in bytes == 2148 TextView showTx = new TextView(context); showTx.setText(step != 4 ? strCahoots : Hex.toHexString(transaction.bitcoinSerialize())); showTx.setTextIsSelectable(true); showTx.setPadding(40, 10, 40, 10); showTx.setTextSize(18.0f); LinearLayout hexLayout = new LinearLayout(context); hexLayout.setOrientation(LinearLayout.VERTICAL); hexLayout.addView(showTx); String title = context.getString(R.string.cahoots); title += ", "; title += (_step + 1); title += "/5"; AlertDialog.Builder dlg = new AlertDialog.Builder(context) .setTitle(title) .setView(hexLayout) .setCancelable(true) .setPositiveButton(R.string.copy_to_clipboard, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { android.content.ClipboardManager clipboard = (android.content.ClipboardManager)context.getSystemService(android.content.Context.CLIPBOARD_SERVICE); android.content.ClipData clip = null; clip = android.content.ClipData.newPlainText("Cahoots", _step != 4 ? strCahoots : Hex.toHexString(_transaction.bitcoinSerialize())); clipboard.setPrimaryClip(clip); Toast.makeText(context, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show(); } }) .setNegativeButton(R.string.show_qr, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if(strCahoots.length() <= QR_ALPHANUM_CHAR_LIMIT) { final ImageView ivQR = new ImageView(context); Display display = ((Activity)context).getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int imgWidth = Math.max(size.x - 240, 150); Bitmap bitmap = null; QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(strCahoots, null, Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), imgWidth); try { bitmap = qrCodeEncoder.encodeAsBitmap(); } catch (WriterException e) { e.printStackTrace(); } ivQR.setImageBitmap(bitmap); LinearLayout qrLayout = new LinearLayout(context); qrLayout.setOrientation(LinearLayout.VERTICAL); qrLayout.addView(ivQR); new AlertDialog.Builder(context) .setTitle(R.string.cahoots) .setView(qrLayout) .setCancelable(false) .setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }) .setNegativeButton(R.string.share_qr, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String strFileName = AppUtil.getInstance(context).getReceiveQRFilename(); File file = new File(strFileName); if(!file.exists()) { try { file.createNewFile(); } catch(Exception e) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show(); } } file.setReadable(true, false); FileOutputStream fos = null; try { fos = new FileOutputStream(file); } catch(FileNotFoundException fnfe) { ; } if(file != null && fos != null) { Bitmap bitmap = ((BitmapDrawable)ivQR.getDrawable()).getBitmap(); bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos); try { fos.close(); } catch(IOException ioe) { ; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/png"); if (android.os.Build.VERSION.SDK_INT >= 24) { //From API 24 sending FIle on intent ,require custom file provider intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile( context, context.getApplicationContext() .getPackageName() + ".provider", file)); } else { intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); } context.startActivity(Intent.createChooser(intent, context.getText(R.string.send_tx))); } } }).show(); } else { Toast.makeText(context, R.string.tx_too_large_qr, Toast.LENGTH_SHORT).show(); } } }); if(_step == 4) { dlg.setPositiveButton(R.string.broadcast, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); PushTx.getInstance(context).pushTx(Hex.toHexString(_transaction.bitcoinSerialize())); Looper.loop(); } }).start(); } }); dlg.setNeutralButton(R.string.show_tx, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String tx = ""; if(_transaction != null) { tx = _transaction.toString(); } TextView showText = new TextView(context); showText.setText(tx); showText.setTextIsSelectable(true); showText.setPadding(40, 10, 40, 10); showText.setTextSize(18.0f); new AlertDialog.Builder(context) .setTitle(R.string.app_name) .setView(showText) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }).show(); } }); } else if(_step == 3) { dlg.setNeutralButton(R.string.show_tx, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String tx = ""; if(_transaction != null) { tx = _transaction.toString(); } TextView showText = new TextView(context); showText.setText(tx); showText.setTextIsSelectable(true); showText.setPadding(40, 10, 40, 10); showText.setTextSize(18.0f); new AlertDialog.Builder(context) .setTitle(R.string.app_name) .setView(showText) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }).show(); } }); } else { ; } if(!((Activity)context).isFinishing()) { dlg.show(); } } public void doPSBT(final String strPSBT) { String msg = null; PSBT psbt = new PSBT(strPSBT, SamouraiWallet.getInstance().getCurrentNetworkParams()); try { psbt.read(); msg = psbt.dump(); } catch(Exception e) { msg = e.getMessage(); } final EditText edPSBT = new EditText(context); edPSBT.setSingleLine(false); edPSBT.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE); edPSBT.setLines(10); edPSBT.setHint(R.string.PSBT); edPSBT.setGravity(Gravity.START); TextWatcher textWatcher = new TextWatcher() { public void afterTextChanged(Editable s) { edPSBT.setSelection(0); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { ; } public void onTextChanged(CharSequence s, int start, int before, int count) { ; } }; edPSBT.addTextChangedListener(textWatcher); edPSBT.setText(msg); AlertDialog.Builder dlg = new AlertDialog.Builder(context) .setTitle(R.string.app_name) .setMessage(R.string.PSBT) .setView(edPSBT) .setCancelable(true) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!((Activity)context).isFinishing()) { dlg.show(); } } public void doStowaway0(long spendAmount) { // Bob -> Alice, spendAmount in sats NetworkParameters params = SamouraiWallet.getInstance().getCurrentNetworkParams(); // // // step0: B sends spend amount to A, creates step0 // // Stowaway stowaway0 = new Stowaway(spendAmount, params); System.out.println(stowaway0.toJSON().toString()); doCahoots(stowaway0.toJSON().toString()); } private void doStowaway1(Stowaway stowaway0) throws Exception { List<UTXO> utxos = getCahootsUTXO(); // sort in descending order by value Collections.sort(utxos, new UTXO.UTXOComparator()); Log.d("CahootsUtil", "BIP84 utxos:" + utxos.size()); List<UTXO> selectedUTXO = new ArrayList<UTXO>(); long totalContributedAmount = 0L; for(UTXO utxo : utxos) { selectedUTXO.add(utxo); totalContributedAmount += utxo.getValue(); Log.d("CahootsUtil", "BIP84 selected utxo:" + utxo.getValue()); if(totalContributedAmount > stowaway0.getSpendAmount() + SamouraiWallet.bDust.longValue()) { break; } } if(!(totalContributedAmount > stowaway0.getSpendAmount() + SamouraiWallet.bDust.longValue())) { Toast.makeText(context, R.string.cannot_compose_cahoots, Toast.LENGTH_SHORT).show(); return; } Log.d("CahootsUtil", "BIP84 selected utxos:" + selectedUTXO.size()); NetworkParameters params = stowaway0.getParams(); // // // step1: A utxos -> B (take largest that cover amount) // A provides 5750000 // // String zpub = BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr(); HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>> inputsA = new HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>>(); // inputsA.put(outpoint_A0, Triple.of(Hex.decode("0221b719bc26fb49971c7dd328a6c7e4d17dfbf4e2217bee33a65c53ed3daf041e"), FormatsUtil.getInstance().getFingerprintFromXPUB("vpub5Z3hqXewnCbxnMsWygxN8AyjNVJbFeV2VCdDKpTFazdoC29qK4Y5DSQ1aaAPBrsBZ1TzN5va6xGy4eWa9uAqh2AwifuA1eofkedh3eUgF6b"), "M/0/4")); // inputsA.put(outpoint_A1, Triple.of(Hex.decode("020ab261e1a3cf986ecb3cd02299de36295e804fd799934dc5c99dde0d25e71b93"), FormatsUtil.getInstance().getFingerprintFromXPUB("vpub5Z3hqXewnCbxnMsWygxN8AyjNVJbFeV2VCdDKpTFazdoC29qK4Y5DSQ1aaAPBrsBZ1TzN5va6xGy4eWa9uAqh2AwifuA1eofkedh3eUgF6b"), "M/0/2")); for(UTXO utxo : selectedUTXO) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { _TransactionOutPoint _outpoint = new _TransactionOutPoint(outpoint); ECKey eckey = SendFactory.getPrivKey(_outpoint.getAddress()); String path = APIFactory.getInstance(context).getUnspentPaths().get(_outpoint.getAddress()); inputsA.put(_outpoint, Triple.of(eckey.getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(zpub), path)); } } // destination output int idx = BIP84Util.getInstance(context).getWallet().getAccount(0).getReceive().getAddrIdx(); SegwitAddress segwitAddress = BIP84Util.getInstance(context).getAddressAt(0, idx); HashMap<_TransactionOutput, Triple<byte[], byte[], String>> outputsA = new HashMap<_TransactionOutput, Triple<byte[], byte[], String>>(); // byte[] scriptPubKey_A = getScriptPubKey("tb1qewwlc2dksuez3zauf38d82m7uqd4ewkf2avdl8", params); Pair<Byte, byte[]> pair = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", segwitAddress.getBech32AsString()); byte[] scriptPubKey_A = Bech32Segwit.getScriptPubkey(pair.getLeft(), pair.getRight()); _TransactionOutput output_A0 = new _TransactionOutput(params, null, Coin.valueOf(stowaway0.getSpendAmount()), scriptPubKey_A); outputsA.put(output_A0, Triple.of(segwitAddress.getECKey().getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()), "M/0/" + idx)); Stowaway stowaway1 = new Stowaway(stowaway0); stowaway1.inc(inputsA, outputsA, null); doCahoots(stowaway1.toJSON().toString()); } private void doStowaway2(Stowaway stowaway1) throws Exception { Transaction transaction = stowaway1.getTransaction(); Log.d("CahootsUtil", "step2 tx:" + org.spongycastle.util.encoders.Hex.toHexString(transaction.bitcoinSerialize())); // Log.d("CahootsUtil", "input value:" + transaction.getInputs().get(0).getValue().longValue()); int nbIncomingInputs = transaction.getInputs().size(); List<UTXO> utxos = getCahootsUTXO(); // sort in ascending order by value Collections.sort(utxos, new UTXO.UTXOComparator()); Collections.reverse(utxos); Log.d("CahootsUtil", "BIP84 utxos:" + utxos.size()); List<UTXO> selectedUTXO = new ArrayList<UTXO>(); int nbTotalSelectedOutPoints = 0; long totalSelectedAmount = 0L; for(UTXO utxo : utxos) { selectedUTXO.add(utxo); totalSelectedAmount += utxo.getValue(); Log.d("BIP84 selected utxo:", "" + utxo.getValue()); nbTotalSelectedOutPoints += utxo.getOutpoints().size(); if(totalSelectedAmount > FeeUtil.getInstance().estimatedFeeSegwit(0, 0, nbTotalSelectedOutPoints + nbIncomingInputs, 2).longValue() + stowaway1.getSpendAmount() + SamouraiWallet.bDust.longValue()) { // discard "extra" utxo, if any List<UTXO> _selectedUTXO = new ArrayList<UTXO>(); Collections.reverse(selectedUTXO); int _nbTotalSelectedOutPoints = 0; long _totalSelectedAmount = 0L; for(UTXO utxoSel : selectedUTXO) { _selectedUTXO.add(utxoSel); _totalSelectedAmount += utxoSel.getValue(); Log.d("CahootsUtil", "BIP84 post selected utxo:" + utxoSel.getValue()); _nbTotalSelectedOutPoints += utxoSel.getOutpoints().size(); if(_totalSelectedAmount > FeeUtil.getInstance().estimatedFeeSegwit(0, 0, _nbTotalSelectedOutPoints + nbIncomingInputs, 2).longValue() + stowaway1.getSpendAmount() + SamouraiWallet.bDust.longValue()) { selectedUTXO.clear(); selectedUTXO.addAll(_selectedUTXO); totalSelectedAmount = _totalSelectedAmount; nbTotalSelectedOutPoints = _nbTotalSelectedOutPoints; break; } } break; } } if(!(totalSelectedAmount > FeeUtil.getInstance().estimatedFeeSegwit(0, 0, nbTotalSelectedOutPoints + nbIncomingInputs, 2).longValue() + stowaway1.getSpendAmount() + SamouraiWallet.bDust.longValue())) { Toast.makeText(context, R.string.cannot_compose_cahoots, Toast.LENGTH_SHORT).show(); return; } Log.d("CahootsUtil", "BIP84 selected utxos:" + selectedUTXO.size()); long fee = FeeUtil.getInstance().estimatedFeeSegwit(0, 0, nbTotalSelectedOutPoints + nbIncomingInputs, 2).longValue(); Log.d("CahootsUtil", "fee:" + fee); NetworkParameters params = stowaway1.getParams(); // // // step2: B verif, utxos -> A (take smallest that cover amount) // B provides 1000000, 1500000 (250000 change, A input larger) // // String zpub = BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr(); HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>> inputsB = new HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>>(); for(UTXO utxo : selectedUTXO) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { _TransactionOutPoint _outpoint = new _TransactionOutPoint(outpoint); ECKey eckey = SendFactory.getPrivKey(_outpoint.getAddress()); String path = APIFactory.getInstance(context).getUnspentPaths().get(_outpoint.getAddress()); inputsB.put(_outpoint, Triple.of(eckey.getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(zpub), path)); } } Log.d("CahootsUtil", "inputsB:" + inputsB.size()); // change output int idx = BIP84Util.getInstance(context).getWallet().getAccount(0).getChange().getAddrIdx(); SegwitAddress segwitAddress = BIP84Util.getInstance(context).getAddressAt(1, idx); HashMap<_TransactionOutput, Triple<byte[], byte[], String>> outputsB = new HashMap<_TransactionOutput, Triple<byte[], byte[], String>>(); Pair<Byte, byte[]> pair = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", segwitAddress.getBech32AsString()); byte[] scriptPubKey_B = Bech32Segwit.getScriptPubkey(pair.getLeft(), pair.getRight()); _TransactionOutput output_B0 = new _TransactionOutput(params, null, Coin.valueOf((totalSelectedAmount - stowaway1.getSpendAmount()) - fee), scriptPubKey_B); outputsB.put(output_B0, Triple.of(segwitAddress.getECKey().getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()), "M/1/" + idx)); Log.d("CahootsUtil", "outputsB:" + outputsB.size()); Stowaway stowaway2 = new Stowaway(stowaway1); stowaway2.inc(inputsB, outputsB, null); System.out.println("step 2:" + stowaway2.toJSON().toString()); doCahoots(stowaway2.toJSON().toString()); } private void doStowaway3(Stowaway stowaway2) throws Exception { HashMap<String,String> utxo2Address = new HashMap<String,String>(); List<UTXO> utxos = APIFactory.getInstance(context).getUtxos(true); for(UTXO utxo : utxos) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { utxo2Address.put(outpoint.getTxHash().toString() + "-" + outpoint.getTxOutputN(), outpoint.getAddress()); Log.d("CahootsUtil", "outpoint address:" + outpoint.getTxHash().toString() + "-" + outpoint.getTxOutputN() + "," + outpoint.getAddress()); } } Transaction transaction = stowaway2.getPSBT().getTransaction(); HashMap<String,ECKey> keyBag_A = new HashMap<String,ECKey>(); for(TransactionInput input : transaction.getInputs()) { TransactionOutPoint outpoint = input.getOutpoint(); String key = outpoint.getHash().toString() + "-" + outpoint.getIndex(); if(utxo2Address.containsKey(key)) { String address = utxo2Address.get(key); ECKey eckey = SendFactory.getPrivKey(address); keyBag_A.put(outpoint.toString(), eckey); } } // // // step3: A verif, BIP69, sig // // /* HashMap<String,ECKey> keyBag_A = new HashMap<String,ECKey>(); keyBag_A.put(outpoint_A0.toString(), ecKey_A0); keyBag_A.put(outpoint_A1.toString(), ecKey_A1); */ Stowaway stowaway3 = new Stowaway(stowaway2); stowaway3.inc(null, null, keyBag_A); System.out.println("step 3:" + stowaway3.toJSON().toString()); doCahoots(stowaway3.toJSON().toString()); } private void doStowaway4(Stowaway stowaway3) throws Exception { HashMap<String,String> utxo2Address = new HashMap<String,String>(); List<UTXO> utxos = APIFactory.getInstance(context).getUtxos(true); for(UTXO utxo : utxos) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { utxo2Address.put(outpoint.getTxHash().toString() + "-" + outpoint.getTxOutputN(), outpoint.getAddress()); Log.d("CahootsUtil", "outpoint address:" + outpoint.getTxHash().toString() + "-" + outpoint.getTxOutputN() + "," + outpoint.getAddress()); } } Transaction transaction = stowaway3.getPSBT().getTransaction(); HashMap<String,ECKey> keyBag_B = new HashMap<String,ECKey>(); for(TransactionInput input : transaction.getInputs()) { TransactionOutPoint outpoint = input.getOutpoint(); String key = outpoint.getHash().toString() + "-" + outpoint.getIndex(); if(utxo2Address.containsKey(key)) { String address = utxo2Address.get(key); ECKey eckey = SendFactory.getPrivKey(address); keyBag_B.put(outpoint.toString(), eckey); } } // // // step4: B verif, sig, broadcast // // /* HashMap<String,ECKey> keyBag_B = new HashMap<String,ECKey>(); keyBag_B.put(outpoint_B0.toString(), ecKey_B0); keyBag_B.put(outpoint_B1.toString(), ecKey_B1); */ Stowaway stowaway4 = new Stowaway(stowaway3); stowaway4.inc(null, null, keyBag_B); System.out.println("step 4:" + stowaway4.toJSON().toString()); System.out.println("step 4 psbt:" + stowaway4.getPSBT().toString()); System.out.println("step 4 tx:" + stowaway4.getTransaction().toString()); System.out.println("step 4 tx hex:" + Hex.toHexString(stowaway4.getTransaction().bitcoinSerialize())); // Stowaway s = new Stowaway(stowaway4.toJSON()); // System.out.println(s.toJSON().toString()); // broadcast ??? doCahoots(stowaway4.toJSON().toString()); } public void doSTONEWALLx2_0(long spendAmount, String address) { // Bob -> Alice, spendAmount in sats NetworkParameters params = SamouraiWallet.getInstance().getCurrentNetworkParams(); // // // step0: B sends spend amount to A, creates step0 // // STONEWALLx2 stonewall0 = new STONEWALLx2(spendAmount, address, params); System.out.println(stonewall0.toJSON().toString()); doCahoots(stonewall0.toJSON().toString()); } private void doSTONEWALLx2_1(STONEWALLx2 stonewall0) throws Exception { List<UTXO> utxos = getCahootsUTXO(); Collections.shuffle(utxos); Log.d("CahootsUtil", "BIP84 utxos:" + utxos.size()); List<String> seenTxs = new ArrayList<String>(); List<UTXO> selectedUTXO = new ArrayList<UTXO>(); long totalContributedAmount = 0L; for(UTXO utxo : utxos) { UTXO _utxo = new UTXO(); for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { if(!seenTxs.contains(outpoint.getTxHash().toString())) { _utxo.getOutpoints().add(outpoint); seenTxs.add(outpoint.getTxHash().toString()); } } if(_utxo.getOutpoints().size() > 0) { selectedUTXO.add(_utxo); totalContributedAmount += _utxo.getValue(); Log.d("CahootsUtil", "BIP84 selected utxo:" + _utxo.getValue()); } if(totalContributedAmount > stonewall0.getSpendAmount() + SamouraiWallet.bDust.longValue()) { break; } } if(!(totalContributedAmount > stonewall0.getSpendAmount() + SamouraiWallet.bDust.longValue())) { Toast.makeText(context, R.string.cannot_compose_cahoots, Toast.LENGTH_SHORT).show(); return; } Log.d("CahootsUtil", "BIP84 selected utxos:" + selectedUTXO.size()); NetworkParameters params = stonewall0.getParams(); // // // step1: A utxos -> B (take largest that cover amount) // A provides 5750000 // // String zpub = BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr(); HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>> inputsA = new HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>>(); // inputsA.put(outpoint_A0, Triple.of(Hex.decode("0221b719bc26fb49971c7dd328a6c7e4d17dfbf4e2217bee33a65c53ed3daf041e"), FormatsUtil.getInstance().getFingerprintFromXPUB("vpub5Z3hqXewnCbxnMsWygxN8AyjNVJbFeV2VCdDKpTFazdoC29qK4Y5DSQ1aaAPBrsBZ1TzN5va6xGy4eWa9uAqh2AwifuA1eofkedh3eUgF6b"), "M/0/4")); // inputsA.put(outpoint_A1, Triple.of(Hex.decode("020ab261e1a3cf986ecb3cd02299de36295e804fd799934dc5c99dde0d25e71b93"), FormatsUtil.getInstance().getFingerprintFromXPUB("vpub5Z3hqXewnCbxnMsWygxN8AyjNVJbFeV2VCdDKpTFazdoC29qK4Y5DSQ1aaAPBrsBZ1TzN5va6xGy4eWa9uAqh2AwifuA1eofkedh3eUgF6b"), "M/0/2")); for(UTXO utxo : selectedUTXO) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { _TransactionOutPoint _outpoint = new _TransactionOutPoint(outpoint); ECKey eckey = SendFactory.getPrivKey(_outpoint.getAddress()); String path = APIFactory.getInstance(context).getUnspentPaths().get(_outpoint.getAddress()); inputsA.put(_outpoint, Triple.of(eckey.getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(zpub), path)); } } // contributor mix output int idx = BIP84Util.getInstance(context).getWallet().getAccount(0).getReceive().getAddrIdx(); SegwitAddress segwitAddress0 = BIP84Util.getInstance(context).getAddressAt(0, idx); HashMap<_TransactionOutput, Triple<byte[], byte[], String>> outputsA = new HashMap<_TransactionOutput, Triple<byte[], byte[], String>>(); Pair<Byte, byte[]> pair0 = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", segwitAddress0.getBech32AsString()); byte[] scriptPubKey_A0 = Bech32Segwit.getScriptPubkey(pair0.getLeft(), pair0.getRight()); _TransactionOutput output_A0 = new _TransactionOutput(params, null, Coin.valueOf(stonewall0.getSpendAmount()), scriptPubKey_A0); outputsA.put(output_A0, Triple.of(segwitAddress0.getECKey().getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()), "M/0/" + idx)); // contributor is also receiver, check for address re-use here if(segwitAddress0.getBech32AsString().equalsIgnoreCase(stonewall0.getDestination())) { SegwitAddress segwitAddress1 = BIP84Util.getInstance(context).getAddressAt(0, idx + 1); Pair<Byte, byte[]> pair1 = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", segwitAddress1.getBech32AsString()); byte[] scriptPubKey1 = Bech32Segwit.getScriptPubkey(pair1.getLeft(), pair1.getRight()); TransactionOutput output1 = new TransactionOutput(params, null, Coin.valueOf(stonewall0.getSpendAmount()), scriptPubKey1); Transaction tx = stonewall0.getTransaction(); tx.clearOutputs(); tx.addOutput(output1); stonewall0.getPSBT().setTransaction(tx); } // contributor change output idx = BIP84Util.getInstance(context).getWallet().getAccount(0).getChange().getAddrIdx(); SegwitAddress segwitAddress1 = BIP84Util.getInstance(context).getAddressAt(1, idx); Pair<Byte, byte[]> pair1 = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", segwitAddress1.getBech32AsString()); byte[] scriptPubKey_A1 = Bech32Segwit.getScriptPubkey(pair1.getLeft(), pair1.getRight()); _TransactionOutput output_A1 = new _TransactionOutput(params, null, Coin.valueOf(totalContributedAmount - stonewall0.getSpendAmount()), scriptPubKey_A1); outputsA.put(output_A1, Triple.of(segwitAddress1.getECKey().getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()), "M/1/" + idx)); STONEWALLx2 stonewall1 = new STONEWALLx2(stonewall0); stonewall1.inc(inputsA, outputsA, null); doCahoots(stonewall1.toJSON().toString()); } private void doSTONEWALLx2_2(STONEWALLx2 stonewall1) throws Exception { Transaction transaction = stonewall1.getTransaction(); Log.d("CahootsUtil", "step2 tx:" + org.spongycastle.util.encoders.Hex.toHexString(transaction.bitcoinSerialize())); // Log.d("CahootsUtil", "input value:" + transaction.getInputs().get(0).getValue().longValue()); int nbIncomingInputs = transaction.getInputs().size(); List<UTXO> utxos = getCahootsUTXO(); Collections.shuffle(utxos); Log.d("CahootsUtil", "BIP84 utxos:" + utxos.size()); List<String> seenTxs = new ArrayList<String>(); for(TransactionInput input : transaction.getInputs()) { if(!seenTxs.contains(input.getOutpoint().getHash().toString())) { seenTxs.add(input.getOutpoint().getHash().toString()); } } List<UTXO> selectedUTXO = new ArrayList<UTXO>(); int nbTotalSelectedOutPoints = 0; long totalSelectedAmount = 0L; for(UTXO utxo : utxos) { UTXO _utxo = new UTXO(); for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { if(!seenTxs.contains(outpoint.getTxHash().toString())) { _utxo.getOutpoints().add(outpoint); seenTxs.add(outpoint.getTxHash().toString()); } } if(_utxo.getOutpoints().size() > 0) { selectedUTXO.add(_utxo); totalSelectedAmount += _utxo.getValue(); nbTotalSelectedOutPoints += _utxo.getOutpoints().size(); Log.d("CahootsUtil", "BIP84 selected utxo:" + _utxo.getValue()); } if(totalSelectedAmount > FeeUtil.getInstance().estimatedFeeSegwit(0, 0, nbTotalSelectedOutPoints + nbIncomingInputs, 4).longValue() + stonewall1.getSpendAmount() + SamouraiWallet.bDust.longValue()) { break; } } if(!(totalSelectedAmount > FeeUtil.getInstance().estimatedFeeSegwit(0, 0, nbTotalSelectedOutPoints + nbIncomingInputs, 4).longValue() + stonewall1.getSpendAmount() + SamouraiWallet.bDust.longValue())) { Toast.makeText(context, R.string.cannot_compose_cahoots, Toast.LENGTH_SHORT).show(); return; } Log.d("CahootsUtil", "BIP84 selected utxos:" + selectedUTXO.size()); long fee = FeeUtil.getInstance().estimatedFeeSegwit(0, 0, nbTotalSelectedOutPoints + nbIncomingInputs, 4).longValue(); Log.d("CahootsUtil", "fee:" + fee); NetworkParameters params = stonewall1.getParams(); // // // step2: B verif, utxos -> A (take smallest that cover amount) // B provides 1000000, 1500000 (250000 change, A input larger) // // String zpub = BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr(); HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>> inputsB = new HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>>(); for(UTXO utxo : selectedUTXO) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { _TransactionOutPoint _outpoint = new _TransactionOutPoint(outpoint); ECKey eckey = SendFactory.getPrivKey(_outpoint.getAddress()); String path = APIFactory.getInstance(context).getUnspentPaths().get(_outpoint.getAddress()); inputsB.put(_outpoint, Triple.of(eckey.getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(zpub), path)); } } // spender change output int idx = BIP84Util.getInstance(context).getWallet().getAccount(0).getChange().getAddrIdx(); SegwitAddress segwitAddress = BIP84Util.getInstance(context).getAddressAt(1, idx); HashMap<_TransactionOutput, Triple<byte[], byte[], String>> outputsB = new HashMap<_TransactionOutput, Triple<byte[], byte[], String>>(); Pair<Byte, byte[]> pair0 = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", segwitAddress.getBech32AsString()); byte[] scriptPubKey_B0 = Bech32Segwit.getScriptPubkey(pair0.getLeft(), pair0.getRight()); _TransactionOutput output_B0 = new _TransactionOutput(params, null, Coin.valueOf((totalSelectedAmount - stonewall1.getSpendAmount()) - fee), scriptPubKey_B0); outputsB.put(output_B0, Triple.of(segwitAddress.getECKey().getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()), "M/1/" + idx)); // destination mix output /* Pair<Byte, byte[]> pair1 = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", stonewall1.getDestinationAddress()); byte[] scriptPubKey_B1 = Bech32Segwit.getScriptPubkey(pair1.getLeft(), pair1.getRight()); _TransactionOutput output_B1 = new _TransactionOutput(params, null, Coin.valueOf((totalSelectedAmount - stonewall1.getSpendAmount()) - fee), scriptPubKey_B1); outputsB.put(output_B1, Triple.of(segwitAddress.getECKey().getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()), "M/1/" + idx)); */ STONEWALLx2 stonewall2 = new STONEWALLx2(stonewall1); stonewall2.inc(inputsB, outputsB, null); System.out.println("step 2:" + stonewall2.toJSON().toString()); doCahoots(stonewall2.toJSON().toString()); } private void doSTONEWALLx2_3(STONEWALLx2 stonewall2) throws Exception { HashMap<String,String> utxo2Address = new HashMap<String,String>(); List<UTXO> utxos = APIFactory.getInstance(context).getUtxos(true); for(UTXO utxo : utxos) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { utxo2Address.put(outpoint.getTxHash().toString() + "-" + outpoint.getTxOutputN(), outpoint.getAddress()); } } // Transaction transaction = stonewall2.getPSBT().getTransaction(); Transaction transaction = stonewall2.getTransaction(); HashMap<String,ECKey> keyBag_A = new HashMap<String,ECKey>(); for(TransactionInput input : transaction.getInputs()) { TransactionOutPoint outpoint = input.getOutpoint(); String key = outpoint.getHash().toString() + "-" + outpoint.getIndex(); if(utxo2Address.containsKey(key)) { String address = utxo2Address.get(key); ECKey eckey = SendFactory.getPrivKey(address); keyBag_A.put(outpoint.toString(), eckey); } } // // // step3: A verif, BIP69, sig // // /* HashMap<String,ECKey> keyBag_A = new HashMap<String,ECKey>(); keyBag_A.put(outpoint_A0.toString(), ecKey_A0); keyBag_A.put(outpoint_A1.toString(), ecKey_A1); */ STONEWALLx2 stonewall3 = new STONEWALLx2(stonewall2); stonewall3.inc(null, null, keyBag_A); System.out.println("step 3:" + stonewall3.toJSON().toString()); doCahoots(stonewall3.toJSON().toString()); } private void doSTONEWALLx2_4(STONEWALLx2 stonewall3) throws Exception { HashMap<String,String> utxo2Address = new HashMap<String,String>(); List<UTXO> utxos = APIFactory.getInstance(context).getUtxos(true); for(UTXO utxo : utxos) { for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { utxo2Address.put(outpoint.getTxHash().toString() + "-" + outpoint.getTxOutputN(), outpoint.getAddress()); } } // Transaction transaction = stonewall3.getPSBT().getTransaction(); Transaction transaction = stonewall3.getTransaction(); HashMap<String,ECKey> keyBag_B = new HashMap<String,ECKey>(); for(TransactionInput input : transaction.getInputs()) { TransactionOutPoint outpoint = input.getOutpoint(); String key = outpoint.getHash().toString() + "-" + outpoint.getIndex(); if(utxo2Address.containsKey(key)) { String address = utxo2Address.get(key); ECKey eckey = SendFactory.getPrivKey(address); keyBag_B.put(outpoint.toString(), eckey); } } // // // step4: B verif, sig, broadcast // // /* HashMap<String,ECKey> keyBag_B = new HashMap<String,ECKey>(); keyBag_B.put(outpoint_B0.toString(), ecKey_B0); keyBag_B.put(outpoint_B1.toString(), ecKey_B1); */ STONEWALLx2 stonewall4 = new STONEWALLx2(stonewall3); stonewall4.inc(null, null, keyBag_B); System.out.println("step 4:" + stonewall4.toJSON().toString()); System.out.println("step 4 psbt:" + stonewall4.getPSBT().toString()); System.out.println("step 4 tx:" + stonewall4.getTransaction().toString()); System.out.println("step 4 tx hex:" + Hex.toHexString(stonewall4.getTransaction().bitcoinSerialize())); // Stowaway s = new Stowaway(stowaway4.toJSON()); // System.out.println(s.toJSON().toString()); // broadcast ??? doCahoots(stonewall4.toJSON().toString()); } private List<UTXO> getCahootsUTXO() { List<UTXO> ret = new ArrayList<UTXO>(); List<UTXO> _utxos = APIFactory.getInstance(context).getUtxos(true); for(UTXO utxo : _utxos) { String script = Hex.toHexString(utxo.getOutpoints().get(0).getScriptBytes()); if(script.startsWith("0014") && APIFactory.getInstance(context).getUnspentPaths().get(utxo.getOutpoints().get(0).getAddress()) != null) { ret.add(utxo); } } return ret; } public long getCahootsValue() { long ret = 0L; List<UTXO> _utxos = getCahootsUTXO(); for(UTXO utxo : _utxos) { ret += utxo.getValue(); } return ret; } }
CahootsUtil: fix STONEWALLx2 contributor-as-receiver
app/src/main/java/com/samourai/wallet/cahoots/util/CahootsUtil.java
CahootsUtil: fix STONEWALLx2 contributor-as-receiver
<ide><path>pp/src/main/java/com/samourai/wallet/cahoots/util/CahootsUtil.java <ide> <ide> String zpub = BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr(); <ide> HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>> inputsA = new HashMap<_TransactionOutPoint, Triple<byte[], byte[], String>>(); <del>// inputsA.put(outpoint_A0, Triple.of(Hex.decode("0221b719bc26fb49971c7dd328a6c7e4d17dfbf4e2217bee33a65c53ed3daf041e"), FormatsUtil.getInstance().getFingerprintFromXPUB("vpub5Z3hqXewnCbxnMsWygxN8AyjNVJbFeV2VCdDKpTFazdoC29qK4Y5DSQ1aaAPBrsBZ1TzN5va6xGy4eWa9uAqh2AwifuA1eofkedh3eUgF6b"), "M/0/4")); <del>// inputsA.put(outpoint_A1, Triple.of(Hex.decode("020ab261e1a3cf986ecb3cd02299de36295e804fd799934dc5c99dde0d25e71b93"), FormatsUtil.getInstance().getFingerprintFromXPUB("vpub5Z3hqXewnCbxnMsWygxN8AyjNVJbFeV2VCdDKpTFazdoC29qK4Y5DSQ1aaAPBrsBZ1TzN5va6xGy4eWa9uAqh2AwifuA1eofkedh3eUgF6b"), "M/0/2")); <ide> <ide> for(UTXO utxo : selectedUTXO) { <ide> for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) { <ide> // contributor mix output <ide> int idx = BIP84Util.getInstance(context).getWallet().getAccount(0).getReceive().getAddrIdx(); <ide> SegwitAddress segwitAddress0 = BIP84Util.getInstance(context).getAddressAt(0, idx); <add> if(segwitAddress0.getBech32AsString().equalsIgnoreCase(stonewall0.getDestination())) { <add> segwitAddress0 = BIP84Util.getInstance(context).getAddressAt(0, idx + 1); <add> } <ide> HashMap<_TransactionOutput, Triple<byte[], byte[], String>> outputsA = new HashMap<_TransactionOutput, Triple<byte[], byte[], String>>(); <ide> Pair<Byte, byte[]> pair0 = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", segwitAddress0.getBech32AsString()); <ide> byte[] scriptPubKey_A0 = Bech32Segwit.getScriptPubkey(pair0.getLeft(), pair0.getRight()); <ide> _TransactionOutput output_A0 = new _TransactionOutput(params, null, Coin.valueOf(stonewall0.getSpendAmount()), scriptPubKey_A0); <ide> outputsA.put(output_A0, Triple.of(segwitAddress0.getECKey().getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()), "M/0/" + idx)); <del> <del> // contributor is also receiver, check for address re-use here <del> if(segwitAddress0.getBech32AsString().equalsIgnoreCase(stonewall0.getDestination())) { <del> SegwitAddress segwitAddress1 = BIP84Util.getInstance(context).getAddressAt(0, idx + 1); <del> Pair<Byte, byte[]> pair1 = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", segwitAddress1.getBech32AsString()); <del> byte[] scriptPubKey1 = Bech32Segwit.getScriptPubkey(pair1.getLeft(), pair1.getRight()); <del> TransactionOutput output1 = new TransactionOutput(params, null, Coin.valueOf(stonewall0.getSpendAmount()), scriptPubKey1); <del> Transaction tx = stonewall0.getTransaction(); <del> tx.clearOutputs(); <del> tx.addOutput(output1); <del> stonewall0.getPSBT().setTransaction(tx); <del> } <ide> <ide> // contributor change output <ide> idx = BIP84Util.getInstance(context).getWallet().getAccount(0).getChange().getAddrIdx(); <ide> byte[] scriptPubKey_B0 = Bech32Segwit.getScriptPubkey(pair0.getLeft(), pair0.getRight()); <ide> _TransactionOutput output_B0 = new _TransactionOutput(params, null, Coin.valueOf((totalSelectedAmount - stonewall1.getSpendAmount()) - fee), scriptPubKey_B0); <ide> outputsB.put(output_B0, Triple.of(segwitAddress.getECKey().getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()), "M/1/" + idx)); <del> <del> // destination mix output <del> /* <del> Pair<Byte, byte[]> pair1 = Bech32Segwit.decode(SamouraiWallet.getInstance().isTestNet() ? "tb" : "bc", stonewall1.getDestinationAddress()); <del> byte[] scriptPubKey_B1 = Bech32Segwit.getScriptPubkey(pair1.getLeft(), pair1.getRight()); <del> _TransactionOutput output_B1 = new _TransactionOutput(params, null, Coin.valueOf((totalSelectedAmount - stonewall1.getSpendAmount()) - fee), scriptPubKey_B1); <del> outputsB.put(output_B1, Triple.of(segwitAddress.getECKey().getPubKey(), FormatsUtil.getInstance().getFingerprintFromXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()), "M/1/" + idx)); <del> */ <ide> <ide> STONEWALLx2 stonewall2 = new STONEWALLx2(stonewall1); <ide> stonewall2.inc(inputsB, outputsB, null);
Java
apache-2.0
955748bbd2b447b97eda5389e2dd3a5b5b898479
0
linkedin/pinot,linkedin/pinot,linkedin/pinot,linkedin/pinot,linkedin/pinot
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pinot.thirdeye.detection.spi.model; import org.apache.pinot.thirdeye.dataframe.DataFrame; import org.apache.pinot.thirdeye.dataframe.DoubleSeries; import org.apache.pinot.thirdeye.dataframe.LongSeries; import org.apache.pinot.thirdeye.dataframe.util.DataFrameUtils; import static org.apache.pinot.thirdeye.dataframe.util.DataFrameUtils.*; /** * Time series. wrapper object of data frame. Used by baselineProvider to return the predicted time series */ public class TimeSeries { private DataFrame df; public TimeSeries() { this.df = new DataFrame(); } public TimeSeries(LongSeries timestamps, DoubleSeries baselineValues) { this.df = new DataFrame(); this.df.addSeries(COL_TIME, timestamps).setIndex(COL_TIME); this.df.addSeries(DataFrameUtils.COL_VALUE, baselineValues); } public TimeSeries(LongSeries timestamps, DoubleSeries baselineValues, DoubleSeries currentValues, DoubleSeries upperBoundValues, DoubleSeries lowerBoundValues) { this(timestamps, baselineValues); this.df.addSeries(DataFrameUtils.COL_CURRENT, currentValues); this.df.addSeries(DataFrameUtils.COL_UPPER_BOUND, upperBoundValues); this.df.addSeries(DataFrameUtils.COL_LOWER_BOUND, lowerBoundValues); } /** * Add the series into TimeSeries if it exists in the DataFrame. * @param df The source DataFrame. * @param name The series name. */ private static void addSeries(TimeSeries ts, DataFrame df, String name) { if (df.contains(name)) { ts.df.addSeries(name, df.get(name)); } } /** * Add DataFrame into TimeSeries. * @param df The source DataFrame. * @return TimeSeries that contains the predicted values. */ public static TimeSeries fromDataFrame(DataFrame df) { TimeSeries ts = new TimeSeries(); ts.df.addSeries(COL_TIME, df.get(COL_TIME)).setIndex(COL_TIME); addSeries(ts, df, COL_VALUE); addSeries(ts, df, COL_CURRENT); addSeries(ts, df, COL_UPPER_BOUND); addSeries(ts, df, COL_LOWER_BOUND); return ts; } public DoubleSeries getCurrent() { return this.df.getDoubles(DataFrameUtils.COL_CURRENT); } public DoubleSeries getPredictedBaseline() { return this.df.getDoubles(DataFrameUtils.COL_VALUE); } public DoubleSeries getPredictedUpperBound() { return this.df.getDoubles(DataFrameUtils.COL_UPPER_BOUND); } public DoubleSeries getPredictedLowerBound() { return this.df.getDoubles(DataFrameUtils.COL_LOWER_BOUND); } public DataFrame getDataFrame() { return df; } }
thirdeye/thirdeye-pinot/src/main/java/org/apache/pinot/thirdeye/detection/spi/model/TimeSeries.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pinot.thirdeye.detection.spi.model; import org.apache.pinot.thirdeye.dataframe.DataFrame; import org.apache.pinot.thirdeye.dataframe.DoubleSeries; import org.apache.pinot.thirdeye.dataframe.LongSeries; import org.apache.pinot.thirdeye.dataframe.util.DataFrameUtils; import static org.apache.pinot.thirdeye.dataframe.util.DataFrameUtils.*; /** * Time series. wrapper object of data frame. Used by baselineProvider to return the predicted time series */ public class TimeSeries { private DataFrame df; public TimeSeries() { this.df = new DataFrame(); } public TimeSeries(LongSeries timestamps, DoubleSeries baselineValues) { this.df.addSeries(COL_TIME, timestamps).setIndex(COL_TIME); this.df.addSeries(DataFrameUtils.COL_VALUE, baselineValues); } public TimeSeries(LongSeries timestamps, DoubleSeries baselineValues, DoubleSeries currentValues, DoubleSeries upperBoundValues, DoubleSeries lowerBoundValues) { this(timestamps, baselineValues); this.df.addSeries(DataFrameUtils.COL_CURRENT, currentValues); this.df.addSeries(DataFrameUtils.COL_UPPER_BOUND, upperBoundValues); this.df.addSeries(DataFrameUtils.COL_LOWER_BOUND, lowerBoundValues); } /** * Add the series into TimeSeries if it exists in the DataFrame. * @param df The source DataFrame. * @param name The series name. */ private static void addSeries(TimeSeries ts, DataFrame df, String name) { if (df.contains(name)) { ts.df.addSeries(name, df.get(name)); } } /** * Add DataFrame into TimeSeries. * @param df The source DataFrame. * @return TimeSeries that contains the predicted values. */ public static TimeSeries fromDataFrame(DataFrame df) { TimeSeries ts = new TimeSeries(); ts.df.addSeries(COL_TIME, df.get(COL_TIME)).setIndex(COL_TIME); addSeries(ts, df, COL_VALUE); addSeries(ts, df, COL_CURRENT); addSeries(ts, df, COL_UPPER_BOUND); addSeries(ts, df, COL_LOWER_BOUND); return ts; } public DoubleSeries getCurrent() { return this.df.getDoubles(DataFrameUtils.COL_CURRENT); } public DoubleSeries getPredictedBaseline() { return this.df.getDoubles(DataFrameUtils.COL_VALUE); } public DoubleSeries getPredictedUpperBound() { return this.df.getDoubles(DataFrameUtils.COL_UPPER_BOUND); } public DoubleSeries getPredictedLowerBound() { return this.df.getDoubles(DataFrameUtils.COL_LOWER_BOUND); } public DataFrame getDataFrame() { return df; } }
[TE] Fix for TimeSeries constructor (#4150)
thirdeye/thirdeye-pinot/src/main/java/org/apache/pinot/thirdeye/detection/spi/model/TimeSeries.java
[TE] Fix for TimeSeries constructor (#4150)
<ide><path>hirdeye/thirdeye-pinot/src/main/java/org/apache/pinot/thirdeye/detection/spi/model/TimeSeries.java <ide> } <ide> <ide> public TimeSeries(LongSeries timestamps, DoubleSeries baselineValues) { <add> this.df = new DataFrame(); <ide> this.df.addSeries(COL_TIME, timestamps).setIndex(COL_TIME); <ide> this.df.addSeries(DataFrameUtils.COL_VALUE, baselineValues); <ide> }
JavaScript
mit
6b19cda16c0b0b4b2ba86522f11ab8633c46a9f2
0
paultag/poshto
/* sync.js, part of the poŝto suite. * * Copyright (c) Paul Tagliamonte <[email protected]>, 2012 under the terms and * conditions of the Expat license, a copy of which you should have recieved * with this application. */ var Poshto = require("poshto").Poshto, dotcache = process.env.HOME + "/.poshto", account = process.argv[2], mkdirp = require("mkdirp"), config = dotcache + "/conf/" + account + ".json", cache = dotcache + "/mail/" + account + "/", sets = require('simplesets'), fs = require("fs"), settings = JSON.parse(fs.readFileSync(config)), port = ( settings.webserver_port ) ? settings.webserver_port : 3000, poshto = Poshto(settings); function get_folder_folder(folder) { return cache + "folders/" + folder.name + "/" + folder.validity; } function get_mid_hash(message_id) { var path = "", depth = 4; for ( var i = 0; i < depth; ++i ) { path += message_id.substr(i, 1) + "/"; } return path; } function get_mid_path(message) { return cache + "headers/" + get_mid_hash(message); } console.log("Attempting to log in..."); poshto.connect({ "success": function() { console.log("Connected. Opening inbox"); poshto.open({ "failure": function(err) { console.log("Error opening folder: " + err); }, /* We don't declare a success callback, since we can just use the * emited event down below. Then we can just kick off open commands later * and not have to re-implement. */ "folder": "INBOX" }); }, "failure": function(err) { console.log("Error connecting: " + err); } }) poshto.on("message", function(payload) { var message = payload.msg.headers, folder = payload.folder, root = get_folder_folder(folder), idn = root + "/" + payload.msg.id; headers = get_mid_path(message['message-id']); mkdirp(headers); headers += message['message-id']; fs.writeFile(headers, JSON.stringify(message), function(err) { if ( err ) { console.log("Error: " + err); } }); fs.symlink(headers, idn, function(err) { if ( err ) { console.log("Error: " + err); return; } console.log("Wrote out " + headers); }) }); poshto.on("open", function(folder) { var folder_path = get_folder_folder(folder), mails = new sets.Set(folder.mails), exists, to_delete, curptr = folder_path + "/../current"; mkdirp.sync(folder_path); /* Ensure we have a directory to link in. */ cur_stat = fs.stat(curptr, function(err, stat) { if ( err == undefined ) { fs.unlinkSync(curptr); } fs.symlinkSync(folder_path, curptr); }); exists = new sets.Set(fs.readdirSync(folder_path)); to_delete = (exists.difference(mails).array()); to_create = (mails.difference(exists).array()); for ( i in to_delete ) { var file_id = to_delete[i], file = folder_path + "/" + file_id; fs.unlink(file); } if ( to_create.length > 0 ) { poshto.headers({ "folder": folder, "ids": to_create, "failure": function(err) { console.log("Failure to fetch headers: " + err); } }); } }); // vim: tabstop=2 expandtab shiftwidth=2 softtabstop=2
bin/sync.js
/* sync.js, part of the poŝto suite. * * Copyright (c) Paul Tagliamonte <[email protected]>, 2012 under the terms and * conditions of the Expat license, a copy of which you should have recieved * with this application. */ var Poshto = require("poshto").Poshto, dotcache = process.env.HOME + "/.poshto", account = process.argv[2], mkdirp = require("mkdirp"), config = dotcache + "/conf/" + account + ".json", cache = dotcache + "/mail/" + account + "/", sets = require('simplesets'), fs = require("fs"), settings = JSON.parse(fs.readFileSync(config)), port = ( settings.webserver_port ) ? settings.webserver_port : 3000, poshto = Poshto(settings); function get_folder_folder(folder) { return cache + "folders/" + folder.name + "/" + folder.validity; } function get_mid_hash(message_id) { var path = "", depth = 4; for ( var i = 0; i < depth; ++i ) { path += message_id.substr(i, 1) + "/"; } return path; } function get_mid_path(message) { return cache + "headers/" + get_mid_hash(message); } poshto.connect({ "success": function() { console.log("Connected. Opening inbox"); poshto.open({ "failure": function(err) { console.log("Error opening folder: " + err); }, /* We don't declare a success callback, since we can just use the * emited event down below. Then we can just kick off open commands later * and not have to re-implement. */ "folder": "INBOX" }); }, "failure": function(err) { console.log("Error connecting: " + err); } }) poshto.on("message", function(payload) { var message = payload.msg.headers, folder = payload.folder, root = get_folder_folder(folder), idn = root + "/" + payload.msg.id; headers = get_mid_path(message['message-id']); mkdirp(headers); headers += message['message-id']; fs.writeFile(headers, JSON.stringify(message), function(err) { if ( err ) { console.log("Error: " + err); } }); fs.symlink(headers, idn, function(err) { if ( err ) { console.log("Error: " + err); return; } console.log("Wrote out " + headers); }) }); poshto.on("open", function(folder) { var folder_path = get_folder_folder(folder), mails = new sets.Set(folder.mails), exists, to_delete, curptr = folder_path + "/../current"; mkdirp.sync(folder_path); /* Ensure we have a directory to link in. */ cur_stat = fs.stat(curptr, function(err, stat) { if ( err == undefined ) { fs.unlinkSync(curptr); } fs.symlinkSync(folder_path, curptr); }); exists = new sets.Set(fs.readdirSync(folder_path)); to_delete = (exists.difference(mails).array()); to_create = (mails.difference(exists).array()); for ( i in to_delete ) { var file_id = to_delete[i], file = folder_path + "/" + file_id; fs.unlink(file); } if ( to_create.length > 0 ) { poshto.headers({ "folder": folder, "ids": to_create, "failure": function(err) { console.log("Failure to fetch headers: " + err); } }); } }); // vim: tabstop=2 expandtab shiftwidth=2 softtabstop=2
Adding in stupid logging stupid thing for stupid gmail's stupid lockout crap
bin/sync.js
Adding in stupid logging stupid thing for stupid gmail's stupid lockout crap
<ide><path>in/sync.js <ide> return cache + "headers/" + get_mid_hash(message); <ide> } <ide> <add>console.log("Attempting to log in..."); <ide> poshto.connect({ <ide> "success": function() { <ide> console.log("Connected. Opening inbox");
Java
lgpl-2.1
38125040fd83cf94dd3f117cbfc9c2bc857ce6b9
0
CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine
package org.jetel.ctl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TimeZone; import junit.framework.AssertionFailedError; import org.jetel.component.CTLRecordTransform; import org.jetel.component.RecordTransform; import org.jetel.data.DataField; import org.jetel.data.DataRecord; import org.jetel.data.DataRecordFactory; import org.jetel.data.SetVal; import org.jetel.data.lookup.LookupTable; import org.jetel.data.lookup.LookupTableFactory; import org.jetel.data.primitive.Decimal; import org.jetel.data.sequence.Sequence; import org.jetel.data.sequence.SequenceFactory; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.TransformException; import org.jetel.graph.ContextProvider; import org.jetel.graph.ContextProvider.Context; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataFieldContainerType; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataFieldType; import org.jetel.metadata.DataRecordMetadata; import org.jetel.test.CloverTestCase; import org.jetel.util.MiscUtils; import org.jetel.util.bytes.PackedDecimal; import org.jetel.util.crypto.Base64; import org.jetel.util.crypto.Digest; import org.jetel.util.crypto.Digest.DigestType; import org.jetel.util.primitive.TypedProperties; import org.jetel.util.string.StringUtils; import org.joda.time.DateTime; import org.joda.time.Years; public abstract class CompilerTestCase extends CloverTestCase { // ---------- RECORD NAMES ----------- protected static final String INPUT_1 = "firstInput"; protected static final String INPUT_2 = "secondInput"; protected static final String INPUT_3 = "thirdInput"; protected static final String INPUT_4 = "multivalueInput"; protected static final String OUTPUT_1 = "firstOutput"; protected static final String OUTPUT_2 = "secondOutput"; protected static final String OUTPUT_3 = "thirdOutput"; protected static final String OUTPUT_4 = "fourthOutput"; protected static final String OUTPUT_5 = "firstMultivalueOutput"; protected static final String OUTPUT_6 = "secondMultivalueOutput"; protected static final String OUTPUT_7 = "thirdMultivalueOutput"; protected static final String LOOKUP = "lookupMetadata"; protected static final String NAME_VALUE = " HELLO "; protected static final Double AGE_VALUE = 20.25; protected static final String CITY_VALUE = "Chong'La"; protected static final Date BORN_VALUE; protected static final Long BORN_MILLISEC_VALUE; static { Calendar c = Calendar.getInstance(); c.set(2008, 12, 25, 13, 25, 55); c.set(Calendar.MILLISECOND, 333); BORN_VALUE = c.getTime(); BORN_MILLISEC_VALUE = c.getTimeInMillis(); } protected static final Integer VALUE_VALUE = Integer.MAX_VALUE - 10; protected static final Boolean FLAG_VALUE = true; protected static final byte[] BYTEARRAY_VALUE = "Abeceda zedla deda".getBytes(); protected static final BigDecimal CURRENCY_VALUE = new BigDecimal("133.525"); protected static final int DECIMAL_PRECISION = 7; protected static final int DECIMAL_SCALE = 3; protected static final int NORMALIZE_RETURN_OK = 0; public static final int DECIMAL_MAX_PRECISION = 32; public static final MathContext MAX_PRECISION = new MathContext(DECIMAL_MAX_PRECISION,RoundingMode.DOWN); /** Flag to trigger Java compilation */ private boolean compileToJava; protected DataRecord[] inputRecords; protected DataRecord[] outputRecords; protected TransformationGraph graph; public CompilerTestCase(boolean compileToJava) { this.compileToJava = compileToJava; } /** * Method to execute tested CTL code in a way specific to testing scenario. * * Assumes that * {@link #graph}, {@link #inputRecords} and {@link #outputRecords} * have already been set. * * @param compiler */ public abstract void executeCode(ITLCompiler compiler); /** * Method which provides access to specified global variable * * @param varName * global variable to be accessed * @return * */ protected abstract Object getVariable(String varName); protected void check(String varName, Object expectedResult) { assertEquals(varName, expectedResult, getVariable(varName)); } protected void checkEqualValue(String varName, Object expectedResult) { assertTrue(varName, ((Comparable)expectedResult).compareTo(getVariable(varName))==0); } protected void checkEquals(String varName1, String varName2) { assertEquals("Comparing " + varName1 + " and " + varName2 + " : ", getVariable(varName1), getVariable(varName2)); } protected void checkNull(String varName) { assertNull(getVariable(varName)); } private void checkArray(String varName, byte[] expected) { byte[] actual = (byte[]) getVariable(varName); assertTrue("Arrays do not match; expected: " + byteArrayAsString(expected) + " but was " + byteArrayAsString(actual), Arrays.equals(actual, expected)); } private static String byteArrayAsString(byte[] array) { final StringBuilder sb = new StringBuilder("["); for (final byte b : array) { sb.append(b); sb.append(", "); } sb.delete(sb.length() - 2, sb.length()); sb.append(']'); return sb.toString(); } @Override protected void setUp() { // set default locale to English to prevent various parsing errors Locale.setDefault(Locale.ENGLISH); initEngine(); } @Override protected void tearDown() throws Exception { super.tearDown(); inputRecords = null; outputRecords = null; graph = null; } protected TransformationGraph createEmptyGraph() { return new TransformationGraph(); } protected TransformationGraph createDefaultGraph() { TransformationGraph g = createEmptyGraph(); // set the context URL, so that imports can be used g.getRuntimeContext().setContextURL(CompilerTestCase.class.getResource(".")); final HashMap<String, DataRecordMetadata> metadataMap = new HashMap<String, DataRecordMetadata>(); metadataMap.put(INPUT_1, createDefaultMetadata(INPUT_1)); metadataMap.put(INPUT_2, createDefaultMetadata(INPUT_2)); metadataMap.put(INPUT_3, createDefaultMetadata(INPUT_3)); metadataMap.put(INPUT_4, createDefaultMultivalueMetadata(INPUT_4)); metadataMap.put(OUTPUT_1, createDefaultMetadata(OUTPUT_1)); metadataMap.put(OUTPUT_2, createDefaultMetadata(OUTPUT_2)); metadataMap.put(OUTPUT_3, createDefaultMetadata(OUTPUT_3)); metadataMap.put(OUTPUT_4, createDefault1Metadata(OUTPUT_4)); metadataMap.put(OUTPUT_5, createDefaultMultivalueMetadata(OUTPUT_5)); metadataMap.put(OUTPUT_6, createDefaultMultivalueMetadata(OUTPUT_6)); metadataMap.put(OUTPUT_7, createDefaultMultivalueMetadata(OUTPUT_7)); metadataMap.put(LOOKUP, createDefaultMetadata(LOOKUP)); g.addDataRecordMetadata(metadataMap); g.addSequence(createDefaultSequence(g, "TestSequence")); g.addLookupTable(createDefaultLookup(g, "TestLookup")); Properties properties = new Properties(); properties.put("PROJECT", "."); properties.put("DATAIN_DIR", "${PROJECT}/data-in"); properties.put("COUNT", "`1+2`"); properties.put("NEWLINE", "\\n"); g.getGraphParameters().setProperties(properties); initDefaultDictionary(g); return g; } private void initDefaultDictionary(TransformationGraph g) { try { g.getDictionary().init(); g.getDictionary().setValue("s", "string", null); g.getDictionary().setValue("i", "integer", null); g.getDictionary().setValue("l", "long", null); g.getDictionary().setValue("d", "decimal", null); g.getDictionary().setValue("n", "number", null); g.getDictionary().setValue("a", "date", null); g.getDictionary().setValue("b", "boolean", null); g.getDictionary().setValue("y", "byte", null); g.getDictionary().setValue("i211", "integer", new Integer(211)); g.getDictionary().setValue("sVerdon", "string", "Verdon"); g.getDictionary().setValue("l452", "long", new Long(452)); g.getDictionary().setValue("d621", "decimal", new BigDecimal(621)); g.getDictionary().setValue("n9342", "number", new Double(934.2)); g.getDictionary().setValue("a1992", "date", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime()); g.getDictionary().setValue("bTrue", "boolean", Boolean.TRUE); g.getDictionary().setValue("yFib", "byte", new byte[]{1,2,3,5,8,13,21,34,55,89} ); g.getDictionary().setValue("stringList", "list", Arrays.asList("aa", "bb", null, "cc")); g.getDictionary().setContentType("stringList", "string"); g.getDictionary().setValue("dateList", "list", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000))); g.getDictionary().setContentType("dateList", "date"); g.getDictionary().setValue("byteList", "list", Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78})); g.getDictionary().setContentType("byteList", "byte"); } catch (ComponentNotReadyException e) { throw new RuntimeException("Error init default dictionary", e); } } protected Sequence createDefaultSequence(TransformationGraph graph, String name) { Sequence seq = SequenceFactory.createSequence(graph, "PRIMITIVE_SEQUENCE", new Object[] { "Sequence0", graph, name }, new Class[] { String.class, TransformationGraph.class, String.class }); try { seq.checkConfig(new ConfigurationStatus()); seq.init(); } catch (ComponentNotReadyException e) { throw new RuntimeException(e); } return seq; } /** * Creates default lookup table of type SimpleLookupTable with 4 records using default metadata and a composite * lookup key Name+Value. Use field City for testing response. * * @param graph * @param name * @return */ protected LookupTable createDefaultLookup(TransformationGraph graph, String name) { final TypedProperties props = new TypedProperties(); props.setProperty("id", "LookupTable0"); props.setProperty("type", "simpleLookup"); props.setProperty("metadata", LOOKUP); props.setProperty("key", "Name;Value"); props.setProperty("name", name); props.setProperty("keyDuplicates", "true"); /* * The test lookup table is populated from file TestLookup.dat. Alternatively uncomment the populating code * below, however this will most probably break down test_lookup() because free() will wipe away all data and * noone will restore them */ URL dataFile = getClass().getSuperclass().getResource("TestLookup.dat"); if (dataFile == null) { throw new RuntimeException("Unable to populate testing lookup table. File 'TestLookup.dat' not found by classloader"); } props.setProperty("fileURL", dataFile.getFile()); LookupTableFactory.init(); LookupTable lkp = LookupTableFactory.createLookupTable(props); lkp.setGraph(graph); try { lkp.checkConfig(new ConfigurationStatus()); lkp.init(); lkp.preExecute(); } catch (ComponentNotReadyException ex) { throw new RuntimeException(ex); } // ********* POPULATING CODE ************* /*DataRecord lkpRecord = createEmptyRecord(createDefaultMetadata("lookupResponse")); lkpRecord.getField("Name").setValue("Alpha"); lkpRecord.getField("Value").setValue(1); lkpRecord.getField("City").setValue("Andorra la Vella"); lkp.put(lkpRecord); lkpRecord.getField("Name").setValue("Bravo"); lkpRecord.getField("Value").setValue(2); lkpRecord.getField("City").setValue("Bruxelles"); lkp.put(lkpRecord); // duplicate entry lkpRecord.getField("Name").setValue("Charlie"); lkpRecord.getField("Value").setValue(3); lkpRecord.getField("City").setValue("Chamonix"); lkp.put(lkpRecord); lkpRecord.getField("Name").setValue("Charlie"); lkpRecord.getField("Value").setValue(3); lkpRecord.getField("City").setValue("Chomutov"); lkp.put(lkpRecord);*/ // ************ END OF POPULATING CODE ************ return lkp; } /** * Creates records with default structure * * @param name * name for the record to use * @return metadata with default structure */ protected DataRecordMetadata createDefaultMetadata(String name) { DataRecordMetadata ret = new DataRecordMetadata(name); ret.addField(new DataFieldMetadata("Name", DataFieldType.STRING, "|")); ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|")); ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|")); DataFieldMetadata dateField = new DataFieldMetadata("Born", DataFieldType.DATE, "|"); dateField.setFormatStr("yyyy-MM-dd HH:mm:ss"); ret.addField(dateField); ret.addField(new DataFieldMetadata("BornMillisec", DataFieldType.LONG, "|")); ret.addField(new DataFieldMetadata("Value", DataFieldType.INTEGER, "|")); ret.addField(new DataFieldMetadata("Flag", DataFieldType.BOOLEAN, "|")); ret.addField(new DataFieldMetadata("ByteArray", DataFieldType.BYTE, "|")); DataFieldMetadata decimalField = new DataFieldMetadata("Currency", DataFieldType.DECIMAL, "\n"); decimalField.setProperty(DataFieldMetadata.LENGTH_ATTR, String.valueOf(DECIMAL_PRECISION)); decimalField.setProperty(DataFieldMetadata.SCALE_ATTR, String.valueOf(DECIMAL_SCALE)); ret.addField(decimalField); return ret; } /** * Creates records with default structure * * @param name * name for the record to use * @return metadata with default structure */ protected DataRecordMetadata createDefault1Metadata(String name) { DataRecordMetadata ret = new DataRecordMetadata(name); ret.addField(new DataFieldMetadata("Field1", DataFieldType.STRING, "|")); ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|")); ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|")); return ret; } /** * Creates records with default structure * containing multivalue fields. * * @param name * name for the record to use * @return metadata with default structure */ protected DataRecordMetadata createDefaultMultivalueMetadata(String name) { DataRecordMetadata ret = new DataRecordMetadata(name); DataFieldMetadata stringListField = new DataFieldMetadata("stringListField", DataFieldType.STRING, "|"); stringListField.setContainerType(DataFieldContainerType.LIST); ret.addField(stringListField); DataFieldMetadata dateField = new DataFieldMetadata("dateField", DataFieldType.DATE, "|"); ret.addField(dateField); DataFieldMetadata byteField = new DataFieldMetadata("byteField", DataFieldType.BYTE, "|"); ret.addField(byteField); DataFieldMetadata dateListField = new DataFieldMetadata("dateListField", DataFieldType.DATE, "|"); dateListField.setContainerType(DataFieldContainerType.LIST); ret.addField(dateListField); DataFieldMetadata byteListField = new DataFieldMetadata("byteListField", DataFieldType.BYTE, "|"); byteListField.setContainerType(DataFieldContainerType.LIST); ret.addField(byteListField); DataFieldMetadata stringField = new DataFieldMetadata("stringField", DataFieldType.STRING, "|"); ret.addField(stringField); DataFieldMetadata integerMapField = new DataFieldMetadata("integerMapField", DataFieldType.INTEGER, "|"); integerMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(integerMapField); DataFieldMetadata stringMapField = new DataFieldMetadata("stringMapField", DataFieldType.STRING, "|"); stringMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(stringMapField); DataFieldMetadata dateMapField = new DataFieldMetadata("dateMapField", DataFieldType.DATE, "|"); dateMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(dateMapField); DataFieldMetadata byteMapField = new DataFieldMetadata("byteMapField", DataFieldType.BYTE, "|"); byteMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(byteMapField); DataFieldMetadata integerListField = new DataFieldMetadata("integerListField", DataFieldType.INTEGER, "|"); integerListField.setContainerType(DataFieldContainerType.LIST); ret.addField(integerListField); DataFieldMetadata decimalListField = new DataFieldMetadata("decimalListField", DataFieldType.DECIMAL, "|"); decimalListField.setContainerType(DataFieldContainerType.LIST); ret.addField(decimalListField); DataFieldMetadata decimalMapField = new DataFieldMetadata("decimalMapField", DataFieldType.DECIMAL, "|"); decimalMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(decimalMapField); return ret; } /** * Creates new record with specified metadata and sets its field to default values. The record structure will be * created by {@link #createDefaultMetadata(String)} * * @param dataRecordMetadata * metadata to use * @return record initialized to default values */ protected DataRecord createDefaultMultivalueRecord(DataRecordMetadata dataRecordMetadata) { final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata); ret.init(); for (int i = 0; i < ret.getNumFields(); i++) { DataField field = ret.getField(i); DataFieldMetadata fieldMetadata = field.getMetadata(); switch (fieldMetadata.getContainerType()) { case SINGLE: switch (fieldMetadata.getDataType()) { case STRING: field.setValue("John"); break; case DATE: field.setValue(new Date(10000)); break; case BYTE: field.setValue(new byte[] { 0x12, 0x34, 0x56, 0x78 } ); break; default: throw new UnsupportedOperationException("Not implemented."); } break; case LIST: { List<Object> value = new ArrayList<Object>(); switch (fieldMetadata.getDataType()) { case STRING: value.addAll(Arrays.asList("John", "Doe", "Jersey")); break; case INTEGER: value.addAll(Arrays.asList(123, 456, 789)); break; case DATE: value.addAll(Arrays.asList(new Date (12000), new Date(34000))); break; case BYTE: value.addAll(Arrays.asList(new byte[] {0x12, 0x34}, new byte[] {0x56, 0x78})); break; case DECIMAL: value.addAll(Arrays.asList(12.34, 56.78)); break; default: throw new UnsupportedOperationException("Not implemented."); } field.setValue(value); } break; case MAP: { Map<String, Object> value = new HashMap<String, Object>(); switch (fieldMetadata.getDataType()) { case STRING: value.put("firstName", "John"); value.put("lastName", "Doe"); value.put("address", "Jersey"); break; case INTEGER: value.put("count", 123); value.put("max", 456); value.put("sum", 789); break; case DATE: value.put("before", new Date (12000)); value.put("after", new Date(34000)); break; case BYTE: value.put("hash", new byte[] {0x12, 0x34}); value.put("checksum", new byte[] {0x56, 0x78}); break; case DECIMAL: value.put("asset", 12.34); value.put("liability", 56.78); break; default: throw new UnsupportedOperationException("Not implemented."); } field.setValue(value); } break; default: throw new IllegalArgumentException(fieldMetadata.getContainerType().toString()); } } return ret; } /** * Creates new record with specified metadata and sets its field to default values. The record structure will be * created by {@link #createDefaultMetadata(String)} * * @param dataRecordMetadata * metadata to use * @return record initialized to default values */ protected DataRecord createDefaultRecord(DataRecordMetadata dataRecordMetadata) { final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata); ret.init(); SetVal.setString(ret, "Name", NAME_VALUE); SetVal.setDouble(ret, "Age", AGE_VALUE); SetVal.setString(ret, "City", CITY_VALUE); SetVal.setDate(ret, "Born", BORN_VALUE); SetVal.setLong(ret, "BornMillisec", BORN_MILLISEC_VALUE); SetVal.setInt(ret, "Value", VALUE_VALUE); SetVal.setValue(ret, "Flag", FLAG_VALUE); SetVal.setValue(ret, "ByteArray", BYTEARRAY_VALUE); SetVal.setValue(ret, "Currency", CURRENCY_VALUE); return ret; } /** * Allocates new records with structure prescribed by metadata and sets all its fields to <code>null</code> * * @param metadata * structure to use * @return empty record */ protected DataRecord createEmptyRecord(DataRecordMetadata metadata) { DataRecord ret = DataRecordFactory.newRecord(metadata); ret.init(); for (int i = 0; i < ret.getNumFields(); i++) { SetVal.setNull(ret, i); } return ret; } /** * Executes the code using the default graph and records. */ protected void doCompile(String expStr, String testIdentifier) { TransformationGraph graph = createDefaultGraph(); DataRecord[] inRecords = new DataRecord[] { createDefaultRecord(graph.getDataRecordMetadata(INPUT_1)), createDefaultRecord(graph.getDataRecordMetadata(INPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(INPUT_3)), createDefaultMultivalueRecord(graph.getDataRecordMetadata(INPUT_4)) }; DataRecord[] outRecords = new DataRecord[] { createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_1)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_3)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_4)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_5)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_6)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_7)) }; doCompile(expStr, testIdentifier, graph, inRecords, outRecords); } /** * This method should be used to execute a test with a custom graph and custom input and output records. * * To execute a test with the default graph, * use {@link #doCompile(String)} * or {@link #doCompile(String, String)} instead. * * @param expStr * @param testIdentifier * @param graph * @param inRecords * @param outRecords */ protected void doCompile(String expStr, String testIdentifier, TransformationGraph graph, DataRecord[] inRecords, DataRecord[] outRecords) { this.graph = graph; this.inputRecords = inRecords; this.outputRecords = outRecords; // prepend the compilation mode prefix if (compileToJava) { expStr = "//#CTL2:COMPILE\n" + expStr; } print_code(expStr); DataRecordMetadata[] inMetadata = new DataRecordMetadata[inRecords.length]; for (int i = 0; i < inRecords.length; i++) { inMetadata[i] = inRecords[i].getMetadata(); } DataRecordMetadata[] outMetadata = new DataRecordMetadata[outRecords.length]; for (int i = 0; i < outRecords.length; i++) { outMetadata[i] = outRecords[i].getMetadata(); } ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8"); // *** NOTE: please don't remove this commented code. It is used for debugging // *** Uncomment the code to get the compiled Java code during test execution. // *** Please don't commit this code uncommited. // try { // System.out.println(compiler.convertToJava(expStr, CTLRecordTransform.class, testIdentifier)); // } catch (ErrorMessageException e) { // System.out.println("Error parsing CTL code. Unable to output Java translation."); // } List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier); printMessages(messages); if (compiler.errorCount() > 0) { throw new AssertionFailedError("Error in execution. Check standard output for details."); } // *** NOTE: please don't remove this commented code. It is used for debugging // *** Uncomment the code to get the compiled Java code during test execution. // *** Please don't commit this code uncommited. // CLVFStart parseTree = compiler.getStart(); // parseTree.dump(""); executeCode(compiler); } protected void doCompileExpectError(String expStr, String testIdentifier, List<String> errCodes) { graph = createDefaultGraph(); DataRecordMetadata[] inMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(INPUT_1), graph.getDataRecordMetadata(INPUT_2), graph.getDataRecordMetadata(INPUT_3) }; DataRecordMetadata[] outMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(OUTPUT_1), graph.getDataRecordMetadata(OUTPUT_2), graph.getDataRecordMetadata(OUTPUT_3), graph.getDataRecordMetadata(OUTPUT_4) }; // prepend the compilation mode prefix if (compileToJava) { expStr = "//#CTL2:COMPILE\n" + expStr; } print_code(expStr); ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8"); List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier); printMessages(messages); if (compiler.errorCount() == 0) { throw new AssertionFailedError("No errors in parsing. Expected " + errCodes.size() + " errors."); } if (compiler.errorCount() != errCodes.size()) { throw new AssertionFailedError(compiler.errorCount() + " errors in code, but expected " + errCodes.size() + " errors."); } Iterator<String> it = errCodes.iterator(); for (ErrorMessage errorMessage : compiler.getDiagnosticMessages()) { String expectedError = it.next(); if (!expectedError.equals(errorMessage.getErrorMessage())) { throw new AssertionFailedError("Error : \'" + compiler.getDiagnosticMessages().get(0).getErrorMessage() + "\', but expected: \'" + expectedError + "\'"); } } // CLVFStart parseTree = compiler.getStart(); // parseTree.dump(""); // executeCode(compiler); } protected void doCompileExpectError(String testIdentifier, String errCode) { doCompileExpectErrors(testIdentifier, Arrays.asList(errCode)); } protected void doCompileExpectErrors(String testIdentifier, List<String> errCodes) { URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl"); if (importLoc == null) { throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found"); } final StringBuilder sourceCode = new StringBuilder(); String line = null; try { BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream())); while ((line = rd.readLine()) != null) { sourceCode.append(line).append("\n"); } rd.close(); } catch (IOException e) { throw new RuntimeException("I/O error occured when reading source file", e); } doCompileExpectError(sourceCode.toString(), testIdentifier, errCodes); } /** * Method loads tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should * be stored in the same directory as this class. * * @param Test * identifier defining CTL file to load code from */ protected String loadSourceCode(String testIdentifier) { URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl"); if (importLoc == null) { throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found"); } final StringBuilder sourceCode = new StringBuilder(); String line = null; try { BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream())); while ((line = rd.readLine()) != null) { sourceCode.append(line).append("\n"); } rd.close(); } catch (IOException e) { throw new RuntimeException("I/O error occured when reading source file", e); } return sourceCode.toString(); } /** * Method loads and compiles tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should * be stored in the same directory as this class. * * The default graph and records are used for the execution. * * @param Test * identifier defining CTL file to load code from */ protected void doCompile(String testIdentifier) { String sourceCode = loadSourceCode(testIdentifier); doCompile(sourceCode, testIdentifier); } protected void printMessages(List<ErrorMessage> diagnosticMessages) { for (ErrorMessage e : diagnosticMessages) { System.out.println(e); } } /** * Compares two records if they have the same number of fields and identical values in their fields. Does not * consider (or examine) metadata. * * @param lhs * @param rhs * @return true if records have the same number of fields and the same values in them */ protected static boolean recordEquals(DataRecord lhs, DataRecord rhs) { if (lhs == rhs) return true; if (rhs == null) return false; if (lhs == null) { return false; } if (lhs.getNumFields() != rhs.getNumFields()) { return false; } for (int i = 0; i < lhs.getNumFields(); i++) { if (lhs.getField(i).isNull()) { if (!rhs.getField(i).isNull()) { return false; } } else if (!lhs.getField(i).equals(rhs.getField(i))) { return false; } } return true; } public void print_code(String text) { String[] lines = text.split("\n"); System.out.println("\t: 1 2 3 4 5 "); System.out.println("\t:12345678901234567890123456789012345678901234567890123456789"); for (int i = 0; i < lines.length; i++) { System.out.println((i + 1) + "\t:" + lines[i]); } } //----------------------------- TESTS ----------------------------- @SuppressWarnings("unchecked") public void test_operators_unary_record_allowed() { doCompile("test_operators_unary_record_allowed"); check("value", Arrays.asList(14, 16, 16, 65, 63, 63)); check("bornMillisec", Arrays.asList(14L, 16L, 16L, 65L, 63L, 63L)); List<Double> actualAge = (List<Double>) getVariable("age"); double[] expectedAge = {14.123, 16.123, 16.123, 65.789, 63.789, 63.789}; for (int i = 0; i < actualAge.size(); i++) { assertEquals("age[" + i + "]", expectedAge[i], actualAge.get(i), 0.0001); } check("currency", Arrays.asList( new BigDecimal(BigInteger.valueOf(12500), 3), new BigDecimal(BigInteger.valueOf(14500), 3), new BigDecimal(BigInteger.valueOf(14500), 3), new BigDecimal(BigInteger.valueOf(65432), 3), new BigDecimal(BigInteger.valueOf(63432), 3), new BigDecimal(BigInteger.valueOf(63432), 3) )); } @SuppressWarnings("unchecked") public void test_dynamiclib_compare() { doCompile("test_dynamic_compare"); String varName = "compare"; List<Integer> compareResult = (List<Integer>) getVariable(varName); for (int i = 0; i < compareResult.size(); i++) { if ((i % 3) == 0) { assertTrue(varName + "[" + i + "]", compareResult.get(i) > 0); } else if ((i % 3) == 1) { assertEquals(varName + "[" + i + "]", Integer.valueOf(0), compareResult.get(i)); } else if ((i % 3) == 2) { assertTrue(varName + "[" + i + "]", compareResult.get(i) < 0); } } varName = "compareBooleans"; compareResult = (List<Integer>) getVariable(varName); assertEquals(varName + "[0]", Integer.valueOf(0), compareResult.get(0)); assertTrue(varName + "[1]", compareResult.get(1) > 0); assertTrue(varName + "[2]", compareResult.get(2) < 0); assertEquals(varName + "[3]", Integer.valueOf(0), compareResult.get(3)); } public void test_dynamiclib_compare_expect_error(){ try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.0; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, 'Flagxx', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.0; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, 'Flag', myRec2, 'Flagxx'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = null; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, 'Flag', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = null; " + "firstOutput myRec2; myRec2 = null;" + "integer i = compare(myRec, 'Flag', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.1; " + "firstOutput myRec2; myRec2 = null;" + "integer i = compare(myRec, 'Flag', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "$out.0.Flag = true; " + "$out.1.Age = 11;" + "integer i = compare($out.0, 'Flag', $out.1, 'Age'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.0; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, -1, myRec2, -1 ); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.0; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, 2, myRec2, 2 ); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "$out.0.8 = 12.4d; " + "$out.1.8 = 12.5d;" + "integer i = compare($out.0, 9, $out.1, 9 ); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "$out.0.0 = null; " + "$out.1.0 = null;" + "integer i = compare($out.0, 0, $out.1, 0 ); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } } private void test_dynamic_get_set_loop(String testIdentifier) { doCompile(testIdentifier); check("recordLength", 9); check("value", Arrays.asList(654321, 777777, 654321, 654323, 123456, 112567, 112233)); check("type", Arrays.asList("string", "number", "string", "date", "long", "integer", "boolean", "byte", "decimal")); check("asString", Arrays.asList("1000", "1001.0", "1002", "Thu Jan 01 01:00:01 CET 1970", "1004", "1005", "true", null, "1008.000")); check("isNull", Arrays.asList(false, false, false, false, false, false, false, true, false)); check("fieldName", Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency")); Integer[] indices = new Integer[9]; for (int i = 0; i < indices.length; i++) { indices[i] = i; } check("fieldIndex", Arrays.asList(indices)); // check dynamic write and read with all data types check("booleanVar", true); assertTrue("byteVar", Arrays.equals(new BigInteger("1234567890abcdef", 16).toByteArray(), (byte[]) getVariable("byteVar"))); check("decimalVar", new BigDecimal(BigInteger.valueOf(1000125), 3)); check("integerVar", 1000); check("longVar", 1000000000000L); check("numberVar", 1000.5); check("stringVar", "hello"); check("dateVar", new Date(5000)); // null value Boolean[] someValue = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()]; Arrays.fill(someValue, Boolean.FALSE); check("someValue", Arrays.asList(someValue)); Boolean[] nullValue = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()]; Arrays.fill(nullValue, Boolean.TRUE); check("nullValue", Arrays.asList(nullValue)); String[] asString2 = new String[graph.getDataRecordMetadata(INPUT_1).getNumFields()]; check("asString2", Arrays.asList(asString2)); Boolean[] isNull2 = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()]; Arrays.fill(isNull2, Boolean.TRUE); check("isNull2", Arrays.asList(isNull2)); } public void test_dynamic_get_set_loop() { test_dynamic_get_set_loop("test_dynamic_get_set_loop"); } public void test_dynamic_get_set_loop_alternative() { test_dynamic_get_set_loop("test_dynamic_get_set_loop_alternative"); } public void test_dynamic_invalid() { doCompileExpectErrors("test_dynamic_invalid", Arrays.asList( "Input record cannot be assigned to", "Input record cannot be assigned to" )); } public void test_dynamiclib_getBoolValue(){ doCompile("test_dynamiclib_getBoolValue"); check("ret1", true); check("ret2", true); check("ret3", false); check("ret4", false); check("ret5", null); check("ret6", null); } public void test_dynamiclib_getBoolValue_expect_error(){ try { doCompile("function integer transform(){boolean b = getBoolValue($in.0, 2);return 0;}","test_dynamiclib_getBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){boolean b = getBoolValue($in.0, 'Age');return 0;}","test_dynamiclib_getBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi; fi = null; boolean b = getBoolValue(fi, 6); return 0;}","test_dynamiclib_getBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi; fi = null; boolean b = getBoolValue(fi, 'Flag'); return 0;}","test_dynamiclib_getBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getByteValue(){ doCompile("test_dynamiclib_getByteValue"); checkArray("ret1",CompilerTestCase.BYTEARRAY_VALUE); checkArray("ret2",CompilerTestCase.BYTEARRAY_VALUE); check("ret3", null); check("ret4", null); } public void test_dynamiclib_getByteValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; byte b = getByteValue(fi,7); return 0;}","test_dynamiclib_getByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; byte b = fi.getByteValue('ByteArray'); return 0;}","test_dynamiclib_getByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = $in.0.getByteValue('Age'); return 0;}","test_dynamiclib_getByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = getByteValue($in.0, 0); return 0;}","test_dynamiclib_getByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getDateValue(){ doCompile("test_dynamiclib_getDateValue"); check("ret1", CompilerTestCase.BORN_VALUE); check("ret2", CompilerTestCase.BORN_VALUE); check("ret3", null); check("ret4", null); } public void test_dynamiclib_getDateValue_expect_error(){ try { doCompile("function integer transform(){date d = getDateValue($in.0,1); return 0;}","test_dynamiclib_getDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = getDateValue($in.0,'Age'); return 0;}","test_dynamiclib_getDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; date d = getDateValue(null,'Born'); return 0;}","test_dynamiclib_getDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; date d = getDateValue(null,3); return 0;}","test_dynamiclib_getDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getDecimalValue(){ doCompile("test_dynamiclib_getDecimalValue"); check("ret1", CompilerTestCase.CURRENCY_VALUE); check("ret2", CompilerTestCase.CURRENCY_VALUE); check("ret3", null); check("ret4", null); } public void test_dynamiclib_getDecimalValue_expect_error(){ try { doCompile("function integer transform(){decimal d = getDecimalValue($in.0, 1); return 0;}","test_dynamiclib_getDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal d = getDecimalValue($in.0, 'Age'); return 0;}","test_dynamiclib_getDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; decimal d = getDecimalValue(fi,8); return 0;}","test_dynamiclib_getDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; decimal d = getDecimalValue(fi,'Currency'); return 0;}","test_dynamiclib_getDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getFieldIndex(){ doCompile("test_dynamiclib_getFieldIndex"); check("ret1", 1); check("ret2", 1); check("ret3", -1); } public void test_dynamiclib_getFieldIndex_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; integer int = fi.getFieldIndex('Age'); return 0;}","test_dynamiclib_getFieldIndex_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getFieldLabel(){ doCompile("test_dynamiclib_getFieldLabel"); check("ret1", "Age"); check("ret2", "Name"); check("ret3", "Age"); check("ret4", "Value"); } public void test_dynamiclib_getFieldLabel_expect_error(){ try { doCompile("function integer transform(){string name = getFieldLabel($in.0, -5);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string name = getFieldLabel($in.0, 12);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string name = fi.getFieldLabel(2);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string name = fi.getFieldLabel('Age');return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string name = fi.getFieldLabel('');return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; firstInput fi = null; string name = fi.getFieldLabel(s);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer s = null; firstInput fi = null; string name = fi.getFieldLabel(s);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string name = getFieldLabel($in.0, 'Tristana');return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; string name = getFieldLabel($in.0, s);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer s = null; string name = getFieldLabel($in.0, s);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string name = getFieldLabel($in.0, '');return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getFieldName(){ doCompile("test_dynamiclib_getFieldName"); check("ret1", "Age"); check("ret2", "Name"); } public void test_dynamiclib_getFieldName_expect_error(){ try { doCompile("function integer transform(){string str = getFieldName($in.0, -5); return 0;}","test_dynamiclib_getFieldName_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = getFieldName($in.0, 15); return 0;}","test_dynamiclib_getFieldName_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string str = fi.getFieldName(2); return 0;}","test_dynamiclib_getFieldName_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getFieldType(){ doCompile("test_dynamiclib_getFieldType"); check("ret1", "string"); check("ret2", "number"); } public void test_dynamiclib_getFieldType_expect_error(){ try { doCompile("function integer transform(){string str = getFieldType($in.0, -5); return 0;}","test_dynamiclib_getFieldType_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = getFieldType($in.0, 12); return 0;}","test_dynamiclib_getFieldType_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string str = fi.getFieldType(5); return 0;}","test_dynamiclib_getFieldType_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getIntValue(){ doCompile("test_dynamiclib_getIntValue"); check("ret1", CompilerTestCase.VALUE_VALUE); check("ret2", CompilerTestCase.VALUE_VALUE); check("ret3", CompilerTestCase.VALUE_VALUE); check("ret4", CompilerTestCase.VALUE_VALUE); check("ret5", null); } public void test_dynamiclib_getIntValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; integer i = fi.getIntValue(5); return 0;}","test_dynamiclib_getIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = getIntValue($in.0, 1); return 0;}","test_dynamiclib_getIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = getIntValue($in.0, 'Born'); return 0;}","test_dynamiclib_getIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getLongValue(){ doCompile("test_dynamiclib_getLongValue"); check("ret1", CompilerTestCase.BORN_MILLISEC_VALUE); check("ret2", CompilerTestCase.BORN_MILLISEC_VALUE); check("ret3", null); } public void test_dynamiclib_getLongValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; long l = getLongValue(fi, 4);return 0;} ","test_dynamiclib_getLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long l = getLongValue($in.0, 7);return 0;} ","test_dynamiclib_getLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long l = getLongValue($in.0, 'Age');return 0;} ","test_dynamiclib_getLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getNumValue(){ doCompile("test_dynamiclib_getNumValue"); check("ret1", CompilerTestCase.AGE_VALUE); check("ret2", CompilerTestCase.AGE_VALUE); check("ret3", null); } public void test_dynamiclib_getNumValue_expectValue(){ try { doCompile("function integer transform(){firstInput fi = null; number n = getNumValue(fi, 1); return 0;}","test_dynamiclib_getNumValue_expectValue"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number n = getNumValue($in.0, 4); return 0;}","test_dynamiclib_getNumValue_expectValue"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number n = $in.0.getNumValue('Name'); return 0;}","test_dynamiclib_getNumValue_expectValue"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getStringValue(){ doCompile("test_dynamiclib_getStringValue"); check("ret1", CompilerTestCase.NAME_VALUE); check("ret2", CompilerTestCase.NAME_VALUE); check("ret3", null); } public void test_dynamiclib_getStringValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; string str = getStringValue(fi, 0); return 0;}","test_dynamiclib_getStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = getStringValue($in.0, 5); return 0;}","test_dynamiclib_getStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = $in.0.getStringValue('Age'); return 0;}","test_dynamiclib_getStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getValueAsString(){ doCompile("test_dynamiclib_getValueAsString"); check("ret1", " HELLO "); check("ret2", "20.25"); check("ret3", "Chong'La"); check("ret4", "Sun Jan 25 13:25:55 CET 2009"); check("ret5", "1232886355333"); check("ret6", "2147483637"); check("ret7", "true"); check("ret8", "41626563656461207a65646c612064656461"); check("ret9", "133.525"); check("ret10", null); } public void test_dynamiclib_getValueAsString_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; string str = getValueAsString(fi, 1); return 0;}","test_dynamiclib_getValueAsString_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = getValueAsString($in.0, -1); return 0;}","test_dynamiclib_getValueAsString_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = $in.0.getValueAsString(10); return 0;}","test_dynamiclib_getValueAsString_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_isNull(){ doCompile("test_dynamiclib_isNull"); check("ret1", false); check("ret2", false); check("ret3", true); } public void test_dynamiclib_isNull_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; boolean b = fi.isNull(1); return 0;}","test_dynamiclib_isNull_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){boolean b = $in.0.isNull(-5); return 0;}","test_dynamiclib_isNull_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){boolean b = isNull($in.0,12); return 0;}","test_dynamiclib_isNull_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setBoolValue(){ doCompile("test_dynamiclib_setBoolValue"); check("ret1", null); check("ret2", true); check("ret3", false); } public void test_dynamiclib_setBoolValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setBoolValue(fi,6,true); return 0;}","test_dynamiclib_setBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setBoolValue($out.0,1,true); return 0;}","test_dynamiclib_setBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setBoolValue(15,true); return 0;}","test_dynamiclib_setBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setBoolValue(-1,true); return 0;}","test_dynamiclib_setBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setByteValue() throws UnsupportedEncodingException{ doCompile("test_dynamiclib_setByteValue"); checkArray("ret1", "Urgot".getBytes("UTF-8")); check("ret2", null); } public void test_dynamiclib_setByteValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi =null; setByteValue(fi,7,str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setByteValue($out.0, 1, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setByteValue($out.0, 12, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setByteValue(-2, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setDateValue(){ doCompile("test_dynamiclib_setDateValue"); Calendar cal = Calendar.getInstance(); cal.set(2006,10,12,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret1", cal.getTime()); check("ret2", null); } public void test_dynamiclib_setDateValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setDateValue(fi,'Born', null);return 0;}","test_dynamiclib_setDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setDateValue($out.0,1, null);return 0;}","test_dynamiclib_setDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setDateValue($out.0,-2, null);return 0;}","test_dynamiclib_setDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setDateValue(12, null);return 0;}","test_dynamiclib_setDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setDecimalValue(){ doCompile("test_dynamiclib_setDecimalValue"); check("ret1", new BigDecimal("12.300")); check("ret2", null); } public void test_dynamiclib_setDecimalValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setDecimalValue(fi, 'Currency', 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setDecimalValue($out.0, 'Name', 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setDecimalValue(-1, 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setDecimalValue(15, 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setIntValue(){ doCompile("test_dynamiclib_setIntValue"); check("ret1", 90); check("ret2", null); } public void test_dynamiclib_setIntValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi =null; setIntValue(fi,5,null);return 0;}","test_dynamiclib_setIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setIntValue($out.0,4,90);return 0;}","test_dynamiclib_setIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setIntValue($out.0,-2,90);return 0;}","test_dynamiclib_setIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setIntValue(15,90);return 0;}","test_dynamiclib_setIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setLongValue(){ doCompile("test_dynamiclib_setLongValue"); check("ret1", 1565486L); check("ret2", null); } public void test_dynamiclib_setLongValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setLongValue(fi, 4, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setLongValue($out.0, 0, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setLongValue($out.0, -1, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setLongValue(12, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setNumValue(){ doCompile("test_dynamiclib_setNumValue"); check("ret1", 12.5d); check("ret2", null); } public void test_dynamiclib_setNumValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setNumValue(fi, 'Age', 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setNumValue($out.0, 'Name', 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setNumValue($out.0, -1, 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setNumValue(11, 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setStringValue(){ doCompile("test_dynamiclib_setStringValue"); check("ret1", "Zac"); check("ret2", null); } public void test_dynamiclib_setStringValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setStringValue(fi, 'Name', 'Draven'); return 0;}","test_dynamiclib_setStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setStringValue($out.0, 'Age', 'Soraka'); return 0;}","test_dynamiclib_setStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setStringValue($out.0, -1, 'Rengar'); return 0;}","test_dynamiclib_setStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setStringValue(11, 'Vaigar'); return 0;}","test_dynamiclib_setStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_return_constants() { // test case for issue 2257 System.out.println("Return constants test:"); doCompile("test_return_constants"); check("skip", RecordTransform.SKIP); check("all", RecordTransform.ALL); check("ok", NORMALIZE_RETURN_OK); check("stop", RecordTransform.STOP); } public void test_ambiguous() { // built-in toString function doCompileExpectError("test_ambiguous_toString", "Function 'toString' is ambiguous"); // built-in join function doCompileExpectError("test_ambiguous_join", "Function 'join' is ambiguous"); // locally defined functions doCompileExpectError("test_ambiguous_localFunctions", "Function 'local' is ambiguous"); // locally overloaded built-in getUrlPath() function doCompileExpectError("test_ambiguous_combined", "Function 'getUrlPath' is ambiguous"); // swapped arguments - non null ambiguity doCompileExpectError("test_ambiguous_swapped", "Function 'swapped' is ambiguous"); // primitive type widening; the test depends on specific values of the type distance function, can be removed doCompileExpectError("test_ambiguous_widening", "Function 'widening' is ambiguous"); } public void test_raise_error_terminal() { // test case for issue 2337 doCompile("test_raise_error_terminal"); } public void test_raise_error_nonliteral() { // test case for issue CL-2071 doCompile("test_raise_error_nonliteral"); } public void test_case_unique_check() { // test case for issue 2515 doCompileExpectErrors("test_case_unique_check", Arrays.asList("Duplicate case", "Duplicate case")); } public void test_case_unique_check2() { // test case for issue 2515 doCompileExpectErrors("test_case_unique_check2", Arrays.asList("Duplicate case", "Duplicate case")); } public void test_case_unique_check3() { doCompileExpectError("test_case_unique_check3", "Default case is already defined"); } public void test_rvalue_for_append() { // test case for issue 3956 doCompile("test_rvalue_for_append"); check("a", Arrays.asList("1", "2")); check("b", Arrays.asList("a", "b", "c")); check("c", Arrays.asList("1", "2", "a", "b", "c")); } public void test_rvalue_for_map_append() { // test case for issue 3960 doCompile("test_rvalue_for_map_append"); HashMap<Integer, String> map1instance = new HashMap<Integer, String>(); map1instance.put(1, "a"); map1instance.put(2, "b"); HashMap<Integer, String> map2instance = new HashMap<Integer, String>(); map2instance.put(3, "c"); map2instance.put(4, "d"); HashMap<Integer, String> map3instance = new HashMap<Integer, String>(); map3instance.put(1, "a"); map3instance.put(2, "b"); map3instance.put(3, "c"); map3instance.put(4, "d"); check("map1", map1instance); check("map2", map2instance); check("map3", map3instance); } public void test_global_field_access() { // test case for issue 3957 doCompileExpectError("test_global_field_access", "Unable to access record field in global scope"); } public void test_global_scope() { // test case for issue 5006 doCompile("test_global_scope"); check("len", "Kokon".length()); } //TODO Implement /*public void test_new() { doCompile("test_new"); }*/ public void test_parser() { System.out.println("\nParser test:"); doCompile("test_parser"); } public void test_ref_res_import() { System.out.println("\nSpecial character resolving (import) test:"); URL importLoc = getClass().getSuperclass().getResource("test_ref_res.ctl"); String expStr = "import '" + importLoc + "';\n"; doCompile(expStr, "test_ref_res_import"); } public void test_ref_res_noimport() { System.out.println("\nSpecial character resolving (no import) test:"); doCompile("test_ref_res"); } public void test_import() { System.out.println("\nImport test:"); URL importLoc = getClass().getSuperclass().getResource("import.ctl"); String expStr = "import '" + importLoc + "';\n"; importLoc = getClass().getSuperclass().getResource("other.ctl"); expStr += "import '" + importLoc + "';\n" + "integer sumInt;\n" + "function integer transform() {\n" + " if (a == 3) {\n" + " otherImportVar++;\n" + " }\n" + " sumInt = sum(a, otherImportVar);\n" + " return 0;\n" + "}\n"; doCompile(expStr, "test_import"); } public void test_scope() throws ComponentNotReadyException, TransformException { System.out.println("\nMapping test:"); // String expStr = // "function string computeSomething(int n) {\n" + // " string s = '';\n" + // " do {\n" + // " int i = n--;\n" + // " s = s + '-' + i;\n" + // " } while (n > 0)\n" + // " return s;" + // "}\n\n" + // "function int transform() {\n" + // " printErr(computeSomething(10));\n" + // " return 0;\n" + // "}"; URL importLoc = getClass().getSuperclass().getResource("samplecode.ctl"); String expStr = "import '" + importLoc + "';\n"; // "function int getIndexOfOffsetStart(string encodedDate) {\n" + // "int offsetStart;\n" + // "int actualLastMinus;\n" + // "int lastMinus = -1;\n" + // "if ( index_of(encodedDate, '+') != -1 )\n" + // " return index_of(encodedDate, '+');\n" + // "do {\n" + // " actualLastMinus = index_of(encodedDate, '-', lastMinus+1);\n" + // " if ( actualLastMinus != -1 )\n" + // " lastMinus = actualLastMinus;\n" + // "} while ( actualLastMinus != -1 )\n" + // "return lastMinus;\n" + // "}\n" + // "function int transform() {\n" + // " getIndexOfOffsetStart('2009-04-24T08:00:00-05:00');\n" + // " return 0;\n" + // "}\n"; doCompile(expStr, "test_scope"); } //-------------------------- Data Types Tests --------------------- public void test_type_void() { doCompileExpectErrors("test_type_void", Arrays.asList("Syntax error on token 'void'", "Variable 'voidVar' is not declared", "Variable 'voidVar' is not declared", "Syntax error on token 'void'")); } public void test_type_integer() { doCompile("test_type_integer"); check("i", 0); check("j", -1); check("field", VALUE_VALUE); checkNull("nullValue"); check("varWithInitializer", 123); checkNull("varWithNullInitializer"); } public void test_type_integer_edge() { String testExpression = "integer minInt;\n"+ "integer maxInt;\n"+ "function integer transform() {\n" + "minInt=" + Integer.MIN_VALUE + ";\n" + "printErr(minInt, true);\n" + "maxInt=" + Integer.MAX_VALUE + ";\n" + "printErr(maxInt, true);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_int_edge"); check("minInt", Integer.MIN_VALUE); check("maxInt", Integer.MAX_VALUE); } public void test_type_long() { doCompile("test_type_long"); check("i", Long.valueOf(0)); check("j", Long.valueOf(-1)); check("field", BORN_MILLISEC_VALUE); check("def", Long.valueOf(0)); checkNull("nullValue"); check("varWithInitializer", 123L); checkNull("varWithNullInitializer"); } public void test_type_long_edge() { String expStr = "long minLong;\n"+ "long maxLong;\n"+ "function integer transform() {\n" + "minLong=" + (Long.MIN_VALUE) + "L;\n" + "printErr(minLong);\n" + "maxLong=" + (Long.MAX_VALUE) + "L;\n" + "printErr(maxLong);\n" + "return 0;\n" + "}\n"; doCompile(expStr,"test_long_edge"); check("minLong", Long.MIN_VALUE); check("maxLong", Long.MAX_VALUE); } public void test_type_decimal() { doCompile("test_type_decimal"); check("i", new BigDecimal(0, MAX_PRECISION)); check("j", new BigDecimal(-1, MAX_PRECISION)); check("field", CURRENCY_VALUE); check("def", new BigDecimal(0, MAX_PRECISION)); checkNull("nullValue"); check("varWithInitializer", new BigDecimal("123.35", MAX_PRECISION)); checkNull("varWithNullInitializer"); check("varWithInitializerNoDist", new BigDecimal(123.35, MAX_PRECISION)); } public void test_type_decimal_edge() { String testExpression = "decimal minLong;\n"+ "decimal maxLong;\n"+ "decimal minLongNoDist;\n"+ "decimal maxLongNoDist;\n"+ "decimal minDouble;\n"+ "decimal maxDouble;\n"+ "decimal minDoubleNoDist;\n"+ "decimal maxDoubleNoDist;\n"+ "function integer transform() {\n" + "minLong=" + String.valueOf(Long.MIN_VALUE) + "d;\n" + "printErr(minLong);\n" + "maxLong=" + String.valueOf(Long.MAX_VALUE) + "d;\n" + "printErr(maxLong);\n" + "minLongNoDist=" + String.valueOf(Long.MIN_VALUE) + "L;\n" + "printErr(minLongNoDist);\n" + "maxLongNoDist=" + String.valueOf(Long.MAX_VALUE) + "L;\n" + "printErr(maxLongNoDist);\n" + // distincter will cause the double-string be parsed into exact representation within BigDecimal "minDouble=" + String.valueOf(Double.MIN_VALUE) + "D;\n" + "printErr(minDouble);\n" + "maxDouble=" + String.valueOf(Double.MAX_VALUE) + "D;\n" + "printErr(maxDouble);\n" + // no distincter will cause the double-string to be parsed into inexact representation within double // then to be assigned into BigDecimal (which will extract only MAX_PRECISION digits) "minDoubleNoDist=" + String.valueOf(Double.MIN_VALUE) + ";\n" + "printErr(minDoubleNoDist);\n" + "maxDoubleNoDist=" + String.valueOf(Double.MAX_VALUE) + ";\n" + "printErr(maxDoubleNoDist);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_decimal_edge"); check("minLong", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION)); check("maxLong", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION)); check("minLongNoDist", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION)); check("maxLongNoDist", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION)); // distincter will cause the MIN_VALUE to be parsed into exact representation (i.e. 4.9E-324) check("minDouble", new BigDecimal(String.valueOf(Double.MIN_VALUE), MAX_PRECISION)); check("maxDouble", new BigDecimal(String.valueOf(Double.MAX_VALUE), MAX_PRECISION)); // no distincter will cause MIN_VALUE to be parsed into double inexact representation and extraction of // MAX_PRECISION digits (i.e. 4.94065.....E-324) check("minDoubleNoDist", new BigDecimal(Double.MIN_VALUE, MAX_PRECISION)); check("maxDoubleNoDist", new BigDecimal(Double.MAX_VALUE, MAX_PRECISION)); } public void test_type_number() { doCompile("test_type_number"); check("i", Double.valueOf(0)); check("j", Double.valueOf(-1)); check("field", AGE_VALUE); check("def", Double.valueOf(0)); checkNull("nullValue"); checkNull("varWithNullInitializer"); } public void test_type_number_edge() { String testExpression = "number minDouble;\n" + "number maxDouble;\n"+ "function integer transform() {\n" + "minDouble=" + Double.MIN_VALUE + ";\n" + "printErr(minDouble);\n" + "maxDouble=" + Double.MAX_VALUE + ";\n" + "printErr(maxDouble);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_number_edge"); check("minDouble", Double.valueOf(Double.MIN_VALUE)); check("maxDouble", Double.valueOf(Double.MAX_VALUE)); } public void test_type_string() { doCompile("test_type_string"); check("i","0"); check("helloEscaped", "hello\\nworld"); check("helloExpanded", "hello\nworld"); check("fieldName", NAME_VALUE); check("fieldCity", CITY_VALUE); check("escapeChars", "a\u0101\u0102A"); check("doubleEscapeChars", "a\\u0101\\u0102A"); check("specialChars", "špeciálne značky s mäkčeňom môžu byť"); check("dQescapeChars", "a\u0101\u0102A"); //TODO:Is next test correct? check("dQdoubleEscapeChars", "a\\u0101\\u0102A"); check("dQspecialChars", "špeciálne značky s mäkčeňom môžu byť"); check("empty", ""); check("def", ""); checkNull("varWithNullInitializer"); } public void test_type_string_long() { int length = 1000; StringBuilder tmp = new StringBuilder(length); for (int i = 0; i < length; i++) { tmp.append(i % 10); } String testExpression = "string longString;\n" + "function integer transform() {\n" + "longString=\"" + tmp + "\";\n" + "printErr(longString);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_string_long"); check("longString", String.valueOf(tmp)); } public void test_type_date() throws Exception { doCompile("test_type_date"); check("d3", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 1).getTime()); check("d2", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3).getTime()); check("d1", new GregorianCalendar(2006, GregorianCalendar.JANUARY, 1, 1, 2, 3).getTime()); check("field", BORN_VALUE); checkNull("nullValue"); check("minValue", new GregorianCalendar(1970, GregorianCalendar.JANUARY, 1, 1, 0, 0).getTime()); checkNull("varWithNullInitializer"); // test with a default time zone set on the GraphRuntimeContext Context context = null; try { tearDown(); setUp(); TransformationGraph graph = new TransformationGraph(); graph.getRuntimeContext().setTimeZone("GMT+8"); context = ContextProvider.registerGraph(graph); doCompile("test_type_date"); Calendar calendar = new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3); calendar.setTimeZone(TimeZone.getTimeZone("GMT+8")); check("d2", calendar.getTime()); calendar.set(2006, 0, 1, 1, 2, 3); check("d1", calendar.getTime()); } finally { ContextProvider.unregister(context); } } public void test_type_boolean() { doCompile("test_type_boolean"); check("b1", true); check("b2", false); check("b3", false); checkNull("nullValue"); checkNull("varWithNullInitializer"); } public void test_type_boolean_compare() { doCompileExpectErrors("test_type_boolean_compare", Arrays.asList( "Operator '>' is not defined for types 'boolean' and 'boolean'", "Operator '>=' is not defined for types 'boolean' and 'boolean'", "Operator '<' is not defined for types 'boolean' and 'boolean'", "Operator '<=' is not defined for types 'boolean' and 'boolean'", "Operator '<' is not defined for types 'boolean' and 'boolean'", "Operator '>' is not defined for types 'boolean' and 'boolean'", "Operator '>=' is not defined for types 'boolean' and 'boolean'", "Operator '<=' is not defined for types 'boolean' and 'boolean'")); } public void test_type_list() { doCompile("test_type_list"); check("intList", Arrays.asList(1, 2, 3, 4, 5, 6)); check("intList2", Arrays.asList(1, 2, 3)); check("stringList", Arrays.asList( "first", "replaced", "third", "fourth", "fifth", "sixth", "extra")); check("stringListCopy", Arrays.asList( "first", "second", "third", "fourth", "fifth", "seventh")); check("stringListCopy2", Arrays.asList( "first", "replaced", "third", "fourth", "fifth", "sixth", "extra")); assertTrue(getVariable("stringList") != getVariable("stringListCopy")); assertEquals(getVariable("stringList"), getVariable("stringListCopy2")); assertEquals(Arrays.asList(false, null, true), getVariable("booleanList")); assertDeepEquals(Arrays.asList(new byte[] {(byte) 0xAB}, null), getVariable("byteList")); assertDeepEquals(Arrays.asList(null, new byte[] {(byte) 0xCD}), getVariable("cbyteList")); assertEquals(Arrays.asList(new Date(12000), null, new Date(34000)), getVariable("dateList")); assertEquals(Arrays.asList(null, new BigDecimal(BigInteger.valueOf(1234), 2)), getVariable("decimalList")); assertEquals(Arrays.asList(12, null, 34), getVariable("intList3")); assertEquals(Arrays.asList(12l, null, 98l), getVariable("longList")); assertEquals(Arrays.asList(12.34, null, 56.78), getVariable("numberList")); assertEquals(Arrays.asList("aa", null, "bb"), getVariable("stringList2")); List<?> decimalList2 = (List<?>) getVariable("decimalList2"); for (Object o: decimalList2) { assertTrue(o instanceof BigDecimal); } List<?> intList4 = (List<?>) getVariable("intList4"); Set<Object> intList4Set = new HashSet<Object>(intList4); assertEquals(3, intList4Set.size()); } public void test_type_list_field() { doCompile("test_type_list_field"); check("copyByValueTest1", "2"); check("copyByValueTest2", "test"); } public void test_type_map_field() { doCompile("test_type_map_field"); Integer copyByValueTest1 = (Integer) getVariable("copyByValueTest1"); assertEquals(new Integer(2), copyByValueTest1); Integer copyByValueTest2 = (Integer) getVariable("copyByValueTest2"); assertEquals(new Integer(100), copyByValueTest2); } /** * The structure of the objects must be exactly the same! * * @param o1 * @param o2 */ private static void assertDeepCopy(Object o1, Object o2) { if (o1 instanceof DataRecord) { assertFalse(o1 == o2); DataRecord r1 = (DataRecord) o1; DataRecord r2 = (DataRecord) o2; for (int i = 0; i < r1.getNumFields(); i++) { assertDeepCopy(r1.getField(i).getValue(), r2.getField(i).getValue()); } } else if (o1 instanceof Map) { assertFalse(o1 == o2); Map<?, ?> m1 = (Map<?, ?>) o1; Map<?, ?> m2 = (Map<?, ?>) o2; for (Object key: m1.keySet()) { assertDeepCopy(m1.get(key), m2.get(key)); } } else if (o1 instanceof List) { assertFalse(o1 == o2); List<?> l1 = (List<?>) o1; List<?> l2 = (List<?>) o2; for (int i = 0; i < l1.size(); i++) { assertDeepCopy(l1.get(i), l2.get(i)); } } else if (o1 instanceof Date) { assertFalse(o1 == o2); // } else if (o1 instanceof byte[]) { // not required anymore // assertFalse(o1 == o2); } } /** * The structure of the objects must be exactly the same! * * @param o1 * @param o2 */ private static void assertDeepEquals(Object o1, Object o2) { if ((o1 == null) && (o2 == null)) { return; } assertTrue((o1 == null) == (o2 == null)); if (o1 instanceof DataRecord) { DataRecord r1 = (DataRecord) o1; DataRecord r2 = (DataRecord) o2; assertEquals(r1.getNumFields(), r2.getNumFields()); for (int i = 0; i < r1.getNumFields(); i++) { assertDeepEquals(r1.getField(i).getValue(), r2.getField(i).getValue()); } } else if (o1 instanceof Map) { Map<?, ?> m1 = (Map<?, ?>) o1; Map<?, ?> m2 = (Map<?, ?>) o2; assertTrue(m1.keySet().equals(m2.keySet())); for (Object key: m1.keySet()) { assertDeepEquals(m1.get(key), m2.get(key)); } } else if (o1 instanceof List) { List<?> l1 = (List<?>) o1; List<?> l2 = (List<?>) o2; assertEquals("size", l1.size(), l2.size()); for (int i = 0; i < l1.size(); i++) { assertDeepEquals(l1.get(i), l2.get(i)); } } else if (o1 instanceof byte[]) { byte[] b1 = (byte[]) o1; byte[] b2 = (byte[]) o2; if (b1 != b2) { if (b1 == null || b2 == null) { assertEquals(b1, b2); } assertEquals("length", b1.length, b2.length); for (int i = 0; i < b1.length; i++) { assertEquals(String.format("[%d]", i), b1[i], b2[i]); } } } else if (o1 instanceof CharSequence) { String s1 = ((CharSequence) o1).toString(); String s2 = ((CharSequence) o2).toString(); assertEquals(s1, s2); } else if ((o1 instanceof Decimal) || (o1 instanceof BigDecimal)) { BigDecimal d1 = o1 instanceof Decimal ? ((Decimal) o1).getBigDecimalOutput() : (BigDecimal) o1; BigDecimal d2 = o2 instanceof Decimal ? ((Decimal) o2).getBigDecimalOutput() : (BigDecimal) o2; assertEquals(d1, d2); } else { assertEquals(o1, o2); } } private void check_assignment_deepcopy_variable_declaration() { Date testVariableDeclarationDate1 = (Date) getVariable("testVariableDeclarationDate1"); Date testVariableDeclarationDate2 = (Date) getVariable("testVariableDeclarationDate2"); byte[] testVariableDeclarationByte1 = (byte[]) getVariable("testVariableDeclarationByte1"); byte[] testVariableDeclarationByte2 = (byte[]) getVariable("testVariableDeclarationByte2"); assertDeepEquals(testVariableDeclarationDate1, testVariableDeclarationDate2); assertDeepEquals(testVariableDeclarationByte1, testVariableDeclarationByte2); assertDeepCopy(testVariableDeclarationDate1, testVariableDeclarationDate2); assertDeepCopy(testVariableDeclarationByte1, testVariableDeclarationByte2); } @SuppressWarnings("unchecked") private void check_assignment_deepcopy_array_access_expression() { { // JJTARRAYACCESSEXPRESSION - List List<String> stringListField1 = (List<String>) getVariable("stringListField1"); DataRecord recordInList1 = (DataRecord) getVariable("recordInList1"); List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1"); List<DataRecord> recordList2 = (List<DataRecord>) getVariable("recordList2"); assertDeepEquals(stringListField1, recordInList1.getField("stringListField").getValue()); assertDeepEquals(recordInList1, recordList1.get(0)); assertDeepEquals(recordList1, recordList2); assertDeepCopy(stringListField1, recordInList1.getField("stringListField").getValue()); assertDeepCopy(recordInList1, recordList1.get(0)); assertDeepCopy(recordList1, recordList2); } { // map of records Date testDate1 = (Date) getVariable("testDate1"); Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1"); DataRecord recordInMap1 = (DataRecord) getVariable("recordInMap1"); DataRecord recordInMap2 = (DataRecord) getVariable("recordInMap2"); Map<Integer, DataRecord> recordMap2 = (Map<Integer, DataRecord>) getVariable("recordMap2"); assertDeepEquals(testDate1, recordInMap1.getField("dateField").getValue()); assertDeepEquals(recordInMap1, recordMap1.get(0)); assertDeepEquals(recordInMap2, recordMap1.get(0)); assertDeepEquals(recordMap1, recordMap2); assertDeepCopy(testDate1, recordInMap1.getField("dateField").getValue()); assertDeepCopy(recordInMap1, recordMap1.get(0)); assertDeepCopy(recordInMap2, recordMap1.get(0)); assertDeepCopy(recordMap1, recordMap2); } { // map of dates Map<Integer, Date> dateMap1 = (Map<Integer, Date>) getVariable("dateMap1"); Date date1 = (Date) getVariable("date1"); Date date2 = (Date) getVariable("date2"); assertDeepCopy(date1, dateMap1.get(0)); assertDeepCopy(date2, dateMap1.get(1)); } { // map of byte arrays Map<Integer, byte[]> byteMap1 = (Map<Integer, byte[]>) getVariable("byteMap1"); byte[] byte1 = (byte[]) getVariable("byte1"); byte[] byte2 = (byte[]) getVariable("byte2"); assertDeepCopy(byte1, byteMap1.get(0)); assertDeepCopy(byte2, byteMap1.get(1)); } { // JJTARRAYACCESSEXPRESSION - Function call List<String> testArrayAccessFunctionCallStringList = (List<String>) getVariable("testArrayAccessFunctionCallStringList"); DataRecord testArrayAccessFunctionCall = (DataRecord) getVariable("testArrayAccessFunctionCall"); Map<String, DataRecord> function_call_original_map = (Map<String, DataRecord>) getVariable("function_call_original_map"); Map<String, DataRecord> function_call_copied_map = (Map<String, DataRecord>) getVariable("function_call_copied_map"); List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list"); List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list"); assertDeepEquals(testArrayAccessFunctionCallStringList, testArrayAccessFunctionCall.getField("stringListField").getValue()); assertEquals(1, function_call_original_map.size()); assertEquals(2, function_call_copied_map.size()); assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall), function_call_original_list); assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall, testArrayAccessFunctionCall), function_call_copied_list); assertDeepEquals(testArrayAccessFunctionCall, function_call_original_map.get("1")); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("1")); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("2")); assertDeepEquals(testArrayAccessFunctionCall, function_call_original_list.get(1)); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(1)); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(2)); assertDeepCopy(testArrayAccessFunctionCall, function_call_original_map.get("1")); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("1")); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("2")); assertDeepCopy(testArrayAccessFunctionCall, function_call_original_list.get(1)); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(1)); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(2)); } // CLO-1210 { check("stringListNull", Arrays.asList((Object) null)); Map<String, String> stringMapNull = new HashMap<String, String>(); stringMapNull.put("a", null); check("stringMapNull", stringMapNull); } } @SuppressWarnings("unchecked") private void check_assignment_deepcopy_field_access_expression() { // field access Date testFieldAccessDate1 = (Date) getVariable("testFieldAccessDate1"); String testFieldAccessString1 = (String) getVariable("testFieldAccessString1"); List<Date> testFieldAccessDateList1 = (List<Date>) getVariable("testFieldAccessDateList1"); List<String> testFieldAccessStringList1 = (List<String>) getVariable("testFieldAccessStringList1"); Map<String, Date> testFieldAccessDateMap1 = (Map<String, Date>) getVariable("testFieldAccessDateMap1"); Map<String, String> testFieldAccessStringMap1 = (Map<String, String>) getVariable("testFieldAccessStringMap1"); DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1"); DataRecord firstMultivalueOutput = outputRecords[4]; DataRecord secondMultivalueOutput = outputRecords[5]; DataRecord thirdMultivalueOutput = outputRecords[6]; assertDeepEquals(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue()); assertDeepEquals(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0)); assertDeepEquals(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0)); assertDeepEquals(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first")); assertDeepEquals(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first")); assertDeepEquals(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue()); assertDeepEquals(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue()); assertDeepEquals(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue()); assertDeepEquals(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue()); assertDeepEquals(testFieldAccessRecord1, thirdMultivalueOutput); assertDeepCopy(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue()); assertDeepCopy(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0)); assertDeepCopy(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0)); assertDeepCopy(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first")); assertDeepCopy(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first")); assertDeepCopy(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue()); assertDeepCopy(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue()); assertDeepCopy(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue()); assertDeepCopy(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue()); assertDeepCopy(testFieldAccessRecord1, thirdMultivalueOutput); } @SuppressWarnings("unchecked") private void check_assignment_deepcopy_member_access_expression() { { // member access - record Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1"); byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1"); List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1"); List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1"); DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1"); DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); } { // member access - record Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1"); byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1"); List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1"); List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1"); DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1"); DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2"); DataRecord testMemberAccessRecord3 = (DataRecord) getVariable("testMemberAccessRecord3"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); assertDeepEquals(testMemberAccessRecord3, testMemberAccessRecord2); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); assertDeepCopy(testMemberAccessRecord3, testMemberAccessRecord2); // dictionary Date dictionaryDate = (Date) graph.getDictionary().getEntry("a").getValue(); byte[] dictionaryByte = (byte[]) graph.getDictionary().getEntry("y").getValue(); List<String> testMemberAccessStringList1 = (List<String>) getVariable("testMemberAccessStringList1"); List<Date> testMemberAccessDateList2 = (List<Date>) getVariable("testMemberAccessDateList2"); List<byte[]> testMemberAccessByteList2 = (List<byte[]>) getVariable("testMemberAccessByteList2"); List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList"); List<Date> dictionaryDateList = (List<Date>) graph.getDictionary().getValue("dateList"); List<byte[]> dictionaryByteList = (List<byte[]>) graph.getDictionary().getValue("byteList"); assertDeepEquals(dictionaryDate, testMemberAccessDate1); assertDeepEquals(dictionaryByte, testMemberAccessByte1); assertDeepEquals(dictionaryStringList, testMemberAccessStringList1); assertDeepEquals(dictionaryDateList, testMemberAccessDateList2); assertDeepEquals(dictionaryByteList, testMemberAccessByteList2); assertDeepCopy(dictionaryDate, testMemberAccessDate1); assertDeepCopy(dictionaryByte, testMemberAccessByte1); assertDeepCopy(dictionaryStringList, testMemberAccessStringList1); assertDeepCopy(dictionaryDateList, testMemberAccessDateList2); assertDeepCopy(dictionaryByteList, testMemberAccessByteList2); // member access - array of records List<DataRecord> testMemberAccessRecordList1 = (List<DataRecord>) getVariable("testMemberAccessRecordList1"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue()); assertDeepEquals(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2)); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue()); assertDeepCopy(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2)); // member access - map of records Map<Integer, DataRecord> testMemberAccessRecordMap1 = (Map<Integer, DataRecord>) getVariable("testMemberAccessRecordMap1"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue()); assertDeepEquals(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2)); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue()); assertDeepCopy(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2)); } } @SuppressWarnings("unchecked") public void test_assignment_deepcopy() { doCompile("test_assignment_deepcopy"); List<DataRecord> secondRecordList = (List<DataRecord>) getVariable("secondRecordList"); assertEquals("before", secondRecordList.get(0).getField("Name").getValue().toString()); List<DataRecord> firstRecordList = (List<DataRecord>) getVariable("firstRecordList"); assertEquals("after", firstRecordList.get(0).getField("Name").getValue().toString()); check_assignment_deepcopy_variable_declaration(); check_assignment_deepcopy_array_access_expression(); check_assignment_deepcopy_field_access_expression(); check_assignment_deepcopy_member_access_expression(); } public void test_assignment_deepcopy_field_access_expression() { doCompile("test_assignment_deepcopy_field_access_expression"); DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1"); DataRecord firstMultivalueOutput = outputRecords[4]; DataRecord secondMultivalueOutput = outputRecords[5]; DataRecord thirdMultivalueOutput = outputRecords[6]; DataRecord multivalueInput = inputRecords[3]; assertDeepEquals(firstMultivalueOutput, testFieldAccessRecord1); assertDeepEquals(secondMultivalueOutput, multivalueInput); assertDeepEquals(thirdMultivalueOutput, secondMultivalueOutput); assertDeepCopy(firstMultivalueOutput, testFieldAccessRecord1); assertDeepCopy(secondMultivalueOutput, multivalueInput); assertDeepCopy(thirdMultivalueOutput, secondMultivalueOutput); } public void test_assignment_array_access_function_call() { doCompile("test_assignment_array_access_function_call"); Map<String, String> originalMap = new HashMap<String, String>(); originalMap.put("a", "b"); Map<String, String> copiedMap = new HashMap<String, String>(originalMap); copiedMap.put("c", "d"); check("originalMap", originalMap); check("copiedMap", copiedMap); } public void test_assignment_array_access_function_call_wrong_type() { doCompileExpectErrors("test_assignment_array_access_function_call_wrong_type", Arrays.asList( "Expression is not a composite type but is resolved to 'string'", "Type mismatch: cannot convert from 'integer' to 'string'", "Cannot convert from 'integer' to string" )); } @SuppressWarnings("unchecked") public void test_assignment_returnvalue() { doCompile("test_assignment_returnvalue"); { List<String> stringList1 = (List<String>) getVariable("stringList1"); List<String> stringList2 = (List<String>) getVariable("stringList2"); List<String> stringList3 = (List<String>) getVariable("stringList3"); List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1"); Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1"); List<String> stringList4 = (List<String>) getVariable("stringList4"); Map<String, Integer> integerMap1 = (Map<String, Integer>) getVariable("integerMap1"); DataRecord record1 = (DataRecord) getVariable("record1"); DataRecord record2 = (DataRecord) getVariable("record2"); DataRecord firstMultivalueOutput = outputRecords[4]; DataRecord secondMultivalueOutput = outputRecords[5]; DataRecord thirdMultivalueOutput = outputRecords[6]; Date dictionaryDate1 = (Date) getVariable("dictionaryDate1"); Date dictionaryDate = (Date) graph.getDictionary().getValue("a"); Date zeroDate = new Date(0); List<String> testReturnValueDictionary2 = (List<String>) getVariable("testReturnValueDictionary2"); List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList"); List<String> testReturnValue10 = (List<String>) getVariable("testReturnValue10"); DataRecord testReturnValue11 = (DataRecord) getVariable("testReturnValue11"); List<String> testReturnValue12 = (List<String>) getVariable("testReturnValue12"); List<String> testReturnValue13 = (List<String>) getVariable("testReturnValue13"); Map<Integer, DataRecord> function_call_original_map = (Map<Integer, DataRecord>) getVariable("function_call_original_map"); Map<Integer, DataRecord> function_call_copied_map = (Map<Integer, DataRecord>) getVariable("function_call_copied_map"); DataRecord function_call_map_newrecord = (DataRecord) getVariable("function_call_map_newrecord"); List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list"); List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list"); DataRecord function_call_list_newrecord = (DataRecord) getVariable("function_call_list_newrecord"); // identifier assertFalse(stringList1.isEmpty()); assertTrue(stringList2.isEmpty()); assertTrue(stringList3.isEmpty()); // array access expression - list assertDeepEquals("unmodified", recordList1.get(0).getField("stringField").getValue()); assertDeepEquals("modified", recordList1.get(1).getField("stringField").getValue()); // array access expression - map assertDeepEquals("unmodified", recordMap1.get(0).getField("stringField").getValue()); assertDeepEquals("modified", recordMap1.get(1).getField("stringField").getValue()); // array access expression - function call assertDeepEquals(null, function_call_original_map.get(2)); assertDeepEquals("unmodified", function_call_map_newrecord.getField("stringField")); assertDeepEquals("modified", function_call_copied_map.get(2).getField("stringField")); assertDeepEquals(Arrays.asList(null, function_call_list_newrecord), function_call_original_list); assertDeepEquals("unmodified", function_call_list_newrecord.getField("stringField")); assertDeepEquals("modified", function_call_copied_list.get(2).getField("stringField")); // field access expression assertFalse(stringList4.isEmpty()); assertTrue(((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).isEmpty()); assertFalse(integerMap1.isEmpty()); assertTrue(((Map<?, ?>) firstMultivalueOutput.getField("integerMapField").getValue()).isEmpty()); assertDeepEquals("unmodified", record1.getField("stringField")); assertDeepEquals("modified", secondMultivalueOutput.getField("stringField").getValue()); assertDeepEquals("unmodified", record2.getField("stringField")); assertDeepEquals("modified", thirdMultivalueOutput.getField("stringField").getValue()); // member access expression - dictionary // There is no function that could modify a date // assertEquals(zeroDate, dictionaryDate); // assertFalse(zeroDate.equals(testReturnValueDictionary1)); assertFalse(testReturnValueDictionary2.isEmpty()); assertTrue(dictionaryStringList.isEmpty()); // member access expression - record assertFalse(testReturnValue10.isEmpty()); assertTrue(((List<?>) testReturnValue11.getField("stringListField").getValue()).isEmpty()); // member access expression - list of records assertFalse(testReturnValue12.isEmpty()); assertTrue(((List<?>) recordList1.get(2).getField("stringListField").getValue()).isEmpty()); // member access expression - map of records assertFalse(testReturnValue13.isEmpty()); assertTrue(((List<?>) recordMap1.get(2).getField("stringListField").getValue()).isEmpty()); } } @SuppressWarnings("unchecked") public void test_type_map() { doCompile("test_type_map"); Map<String, Integer> testMap = (Map<String, Integer>) getVariable("testMap"); assertEquals(Integer.valueOf(1), testMap.get("zero")); assertEquals(Integer.valueOf(2), testMap.get("one")); assertEquals(Integer.valueOf(3), testMap.get("two")); assertEquals(Integer.valueOf(4), testMap.get("three")); assertEquals(4, testMap.size()); Map<Date, String> dayInWeek = (Map<Date, String>) getVariable("dayInWeek"); Calendar c = Calendar.getInstance(); c.set(2009, Calendar.MARCH, 2, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); assertEquals("Monday", dayInWeek.get(c.getTime())); Map<Date, String> dayInWeekCopy = (Map<Date, String>) getVariable("dayInWeekCopy"); c.set(2009, Calendar.MARCH, 3, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); assertEquals("Tuesday", ((Map<Date, String>) getVariable("tuesday")).get(c.getTime())); assertEquals("Tuesday", dayInWeekCopy.get(c.getTime())); c.set(2009, Calendar.MARCH, 4, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); assertEquals("Wednesday", ((Map<Date, String>) getVariable("wednesday")).get(c.getTime())); assertEquals("Wednesday", dayInWeekCopy.get(c.getTime())); assertFalse(dayInWeek.equals(dayInWeekCopy)); { Map<?, ?> preservedOrder = (Map<?, ?>) getVariable("preservedOrder"); assertEquals(100, preservedOrder.size()); int i = 0; for (Map.Entry<?, ?> entry: preservedOrder.entrySet()) { assertEquals("key" + i, entry.getKey()); assertEquals("value" + i, entry.getValue()); i++; } } } public void test_type_record_list() { doCompile("test_type_record_list"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record_list_global() { doCompile("test_type_record_list_global"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record_map() { doCompile("test_type_record_map"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record_map_global() { doCompile("test_type_record_map_global"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record() { doCompile("test_type_record"); // expected result DataRecord expected = createDefaultRecord(createDefaultMetadata("expected")); // simple copy assertTrue(recordEquals(expected, inputRecords[0])); assertTrue(recordEquals(expected, (DataRecord) getVariable("copy"))); // copy and modify expected.getField("Name").setValue("empty"); expected.getField("Value").setValue(321); Calendar c = Calendar.getInstance(); c.set(1987, Calendar.NOVEMBER, 13, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); expected.getField("Born").setValue(c.getTime()); assertTrue(recordEquals(expected, (DataRecord) getVariable("modified"))); // 2x modified copy expected.getField("Name").setValue("not empty"); assertTrue(recordEquals(expected, (DataRecord)getVariable("modified2"))); // no modification by reference is possible assertTrue(recordEquals(expected, (DataRecord)getVariable("modified3"))); expected.getField("Value").setValue(654321); assertTrue(recordEquals(expected, (DataRecord)getVariable("reference"))); assertTrue(getVariable("modified3") != getVariable("reference")); // output record assertTrue(recordEquals(expected, outputRecords[1])); // null record expected.setToNull(); assertTrue(recordEquals(expected, (DataRecord)getVariable("nullRecord"))); } //------------------------ Operator Tests --------------------------- public void test_variables() { doCompile("test_variables"); check("b1", true); check("b2", true); check("b4", "hi"); check("i", 2); } public void test_operator_plus() { doCompile("test_operator_plus"); check("iplusj", 10 + 100); check("lplusm", Long.valueOf(Integer.MAX_VALUE) + Long.valueOf(Integer.MAX_VALUE / 10)); check("mplusl", getVariable("lplusm")); check("mplusi", Long.valueOf(Integer.MAX_VALUE) + 10); check("iplusm", getVariable("mplusi")); check("nplusm1", Double.valueOf(0.1D + 0.001D)); check("nplusj", Double.valueOf(100 + 0.1D)); check("jplusn", getVariable("nplusj")); check("m1plusm", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) + 0.001d)); check("mplusm1", getVariable("m1plusm")); check("dplusd1", new BigDecimal("0.1", MAX_PRECISION).add(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dplusj", new BigDecimal(100, MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("jplusd", getVariable("dplusj")); check("dplusm", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("mplusd", getVariable("dplusm")); check("dplusn", new BigDecimal("0.1").add(new BigDecimal(0.1D, MAX_PRECISION))); check("nplusd", getVariable("dplusn")); check("spluss1", "hello world"); check("splusj", "hello100"); check("jpluss", "100hello"); check("splusm", "hello" + Long.valueOf(Integer.MAX_VALUE)); check("mpluss", Long.valueOf(Integer.MAX_VALUE) + "hello"); check("splusm1", "hello" + Double.valueOf(0.001D)); check("m1pluss", Double.valueOf(0.001D) + "hello"); check("splusd1", "hello" + new BigDecimal("0.0001")); check("d1pluss", new BigDecimal("0.0001", MAX_PRECISION) + "hello"); } public void test_operator_minus() { doCompile("test_operator_minus"); check("iminusj", 10 - 100); check("lminusm", Long.valueOf(Integer.MAX_VALUE / 10) - Long.valueOf(Integer.MAX_VALUE)); check("mminusi", Long.valueOf(Integer.MAX_VALUE - 10)); check("iminusm", 10 - Long.valueOf(Integer.MAX_VALUE)); check("nminusm1", Double.valueOf(0.1D - 0.001D)); check("nminusj", Double.valueOf(0.1D - 100)); check("jminusn", Double.valueOf(100 - 0.1D)); check("m1minusm", Double.valueOf(0.001D - Long.valueOf(Integer.MAX_VALUE))); check("mminusm1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) - 0.001D)); check("dminusd1", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dminusj", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION)); check("jminusd", new BigDecimal(100, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dminusm", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mminusd", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dminusn", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION)); check("nminusd", new BigDecimal(0.1D, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); } public void test_operator_multiply() { doCompile("test_operator_multiply"); check("itimesj", 10 * 100); check("ltimesm", Long.valueOf(Integer.MAX_VALUE) * (Long.valueOf(Integer.MAX_VALUE / 10))); check("mtimesl", getVariable("ltimesm")); check("mtimesi", Long.valueOf(Integer.MAX_VALUE) * 10); check("itimesm", getVariable("mtimesi")); check("ntimesm1", Double.valueOf(0.1D * 0.001D)); check("ntimesj", Double.valueOf(0.1) * 100); check("jtimesn", getVariable("ntimesj")); check("m1timesm", Double.valueOf(0.001d * Long.valueOf(Integer.MAX_VALUE))); check("mtimesm1", getVariable("m1timesm")); check("dtimesd1", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dtimesj", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(100, MAX_PRECISION))); check("jtimesd", getVariable("dtimesj")); check("dtimesm", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mtimesd", getVariable("dtimesm")); check("dtimesn", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(0.1, MAX_PRECISION), MAX_PRECISION)); check("ntimesd", getVariable("dtimesn")); } public void test_operator_divide() { doCompile("test_operator_divide"); check("idividej", 10 / 100); check("ldividem", Long.valueOf(Integer.MAX_VALUE / 10) / Long.valueOf(Integer.MAX_VALUE)); check("mdividei", Long.valueOf(Integer.MAX_VALUE / 10)); check("idividem", 10 / Long.valueOf(Integer.MAX_VALUE)); check("ndividem1", Double.valueOf(0.1D / 0.001D)); check("ndividej", Double.valueOf(0.1D / 100)); check("jdividen", Double.valueOf(100 / 0.1D)); check("m1dividem", Double.valueOf(0.001D / Long.valueOf(Integer.MAX_VALUE))); check("mdividem1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) / 0.001D)); check("ddivided1", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("ddividej", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION)); check("jdivided", new BigDecimal(100, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("ddividem", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mdivided", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("ddividen", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION)); check("ndivided", new BigDecimal(0.1D, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); } public void test_operator_modulus() { doCompile("test_operator_modulus"); check("imoduloj", 10 % 100); check("lmodulom", Long.valueOf(Integer.MAX_VALUE / 10) % Long.valueOf(Integer.MAX_VALUE)); check("mmoduloi", Long.valueOf(Integer.MAX_VALUE % 10)); check("imodulom", 10 % Long.valueOf(Integer.MAX_VALUE)); check("nmodulom1", Double.valueOf(0.1D % 0.001D)); check("nmoduloj", Double.valueOf(0.1D % 100)); check("jmodulon", Double.valueOf(100 % 0.1D)); check("m1modulom", Double.valueOf(0.001D % Long.valueOf(Integer.MAX_VALUE))); check("mmodulom1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) % 0.001D)); check("dmodulod1", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dmoduloj", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION)); check("jmodulod", new BigDecimal(100, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dmodulom", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mmodulod", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dmodulon", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION)); check("nmodulod", new BigDecimal(0.1D, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); } public void test_operators_unary() { doCompile("test_operators_unary"); // postfix operators // int check("intPlusOrig", Integer.valueOf(10)); check("intPlusPlus", Integer.valueOf(10)); check("intPlus", Integer.valueOf(11)); check("intMinusOrig", Integer.valueOf(10)); check("intMinusMinus", Integer.valueOf(10)); check("intMinus", Integer.valueOf(9)); // long check("longPlusOrig", Long.valueOf(10)); check("longPlusPlus", Long.valueOf(10)); check("longPlus", Long.valueOf(11)); check("longMinusOrig", Long.valueOf(10)); check("longMinusMinus", Long.valueOf(10)); check("longMinus", Long.valueOf(9)); // double check("numberPlusOrig", Double.valueOf(10.1)); check("numberPlusPlus", Double.valueOf(10.1)); check("numberPlus", Double.valueOf(11.1)); check("numberMinusOrig", Double.valueOf(10.1)); check("numberMinusMinus", Double.valueOf(10.1)); check("numberMinus", Double.valueOf(9.1)); // decimal check("decimalPlusOrig", new BigDecimal("10.1")); check("decimalPlusPlus", new BigDecimal("10.1")); check("decimalPlus", new BigDecimal("11.1")); check("decimalMinusOrig", new BigDecimal("10.1")); check("decimalMinusMinus", new BigDecimal("10.1")); check("decimalMinus", new BigDecimal("9.1")); // prefix operators // integer check("plusIntOrig", Integer.valueOf(10)); check("plusPlusInt", Integer.valueOf(11)); check("plusInt", Integer.valueOf(11)); check("minusIntOrig", Integer.valueOf(10)); check("minusMinusInt", Integer.valueOf(9)); check("minusInt", Integer.valueOf(9)); check("unaryInt", Integer.valueOf(-10)); // long check("plusLongOrig", Long.valueOf(10)); check("plusPlusLong", Long.valueOf(11)); check("plusLong", Long.valueOf(11)); check("minusLongOrig", Long.valueOf(10)); check("minusMinusLong", Long.valueOf(9)); check("minusLong", Long.valueOf(9)); check("unaryLong", Long.valueOf(-10)); // double check("plusNumberOrig", Double.valueOf(10.1)); check("plusPlusNumber", Double.valueOf(11.1)); check("plusNumber", Double.valueOf(11.1)); check("minusNumberOrig", Double.valueOf(10.1)); check("minusMinusNumber", Double.valueOf(9.1)); check("minusNumber", Double.valueOf(9.1)); check("unaryNumber", Double.valueOf(-10.1)); // decimal check("plusDecimalOrig", new BigDecimal("10.1")); check("plusPlusDecimal", new BigDecimal("11.1")); check("plusDecimal", new BigDecimal("11.1")); check("minusDecimalOrig", new BigDecimal("10.1")); check("minusMinusDecimal", new BigDecimal("9.1")); check("minusDecimal", new BigDecimal("9.1")); check("unaryDecimal", new BigDecimal("-10.1")); // record values assertEquals(101, ((DataRecord) getVariable("plusPlusRecord")).getField("Value").getValue()); assertEquals(101, ((DataRecord) getVariable("recordPlusPlus")).getField("Value").getValue()); assertEquals(101, ((DataRecord) getVariable("modifiedPlusPlusRecord")).getField("Value").getValue()); assertEquals(101, ((DataRecord) getVariable("modifiedRecordPlusPlus")).getField("Value").getValue()); //record as parameter assertEquals(99, ((DataRecord) getVariable("minusMinusRecord")).getField("Value").getValue()); assertEquals(99, ((DataRecord) getVariable("recordMinusMinus")).getField("Value").getValue()); assertEquals(99, ((DataRecord) getVariable("modifiedMinusMinusRecord")).getField("Value").getValue()); assertEquals(99, ((DataRecord) getVariable("modifiedRecordMinusMinus")).getField("Value").getValue()); // logical not check("booleanValue", true); check("negation", false); check("doubleNegation", true); } public void test_operators_unary_record() { doCompileExpectErrors("test_operators_unary_record", Arrays.asList( "Illegal argument to ++/-- operator", "Illegal argument to ++/-- operator", "Illegal argument to ++/-- operator", "Illegal argument to ++/-- operator", "Input record cannot be assigned to", "Input record cannot be assigned to", "Input record cannot be assigned to", "Input record cannot be assigned to" )); } public void test_operator_equal() { doCompile("test_operator_equal"); check("eq0", true); check("eq1", true); check("eq1a", true); check("eq1b", true); check("eq1c", false); check("eq2", true); check("eq3", true); check("eq4", true); check("eq5", true); check("eq6", false); check("eq7", true); check("eq8", false); check("eq9", true); check("eq10", false); check("eq11", true); check("eq12", false); check("eq13", true); check("eq14", false); check("eq15", false); check("eq16", true); check("eq17", false); check("eq18", false); check("eq19", false); // byte check("eq20", true); check("eq21", true); check("eq22", false); check("eq23", false); check("eq24", true); check("eq25", false); check("eq20c", true); check("eq21c", true); check("eq22c", false); check("eq23c", false); check("eq24c", true); check("eq25c", false); check("eq26", true); check("eq27", true); } public void test_operator_non_equal(){ doCompile("test_operator_non_equal"); check("inei", false); check("inej", true); check("jnei", true); check("jnej", false); check("lnei", false); check("inel", false); check("lnej", true); check("jnel", true); check("lnel", false); check("dnei", false); check("ined", false); check("dnej", true); check("jned", true); check("dnel", false); check("lned", false); check("dned", false); check("dned_different_scale", false); } public void test_operator_in() { doCompile("test_operator_in"); check("a", Integer.valueOf(1)); check("haystack", Collections.EMPTY_LIST); check("needle", Integer.valueOf(2)); check("b1", true); check("b2", false); check("h2", Arrays.asList(2.1D, 2.0D, 2.2D)); check("b3", true); check("h3", Arrays.asList("memento", "mori", "memento mori")); check("n3", "memento mori"); check("b4", true); check("ret1", false); check("ret2", true); check("ret3", false); check("ret4", true); check("ret5", false); check("ret6", true); check("ret7", false); check("ret8", true); check("ret9", false); check("ret10", true); check("ret11", false); check("ret12", true); check("ret13", false); check("ret14", true); check("ret15", false); check("ret16", true); check("ret17", false); check("ret18", false); check("ret19", true); check("ret20", false); check("ret21", false); } public void test_operator_in_expect_error(){ try { doCompile("function integer transform(){long[] lList = null; long l = 15l; boolean b = in(l, lList); return 0;}","test_operator_in_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[long, long] lMap = null; long l = 15l; boolean b = in(l, lMap); return 0;}","test_operator_in_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_operator_greater_less() { doCompile("test_operator_greater_less"); check("eq1", true); check("eq2", true); check("eq3", true); check("eq4", false); check("eq5", true); check("eq6", false); check("eq7", true); check("eq8", true); check("eq9", true); } public void test_operator_ternary(){ doCompile("test_operator_ternary"); // simple use check("trueValue", true); check("falseValue", false); check("res1", Integer.valueOf(1)); check("res2", Integer.valueOf(2)); // nesting in positive branch check("res3", Integer.valueOf(1)); check("res4", Integer.valueOf(2)); check("res5", Integer.valueOf(3)); // nesting in negative branch check("res6", Integer.valueOf(2)); check("res7", Integer.valueOf(3)); // nesting in both branches check("res8", Integer.valueOf(1)); check("res9", Integer.valueOf(1)); check("res10", Integer.valueOf(2)); check("res11", Integer.valueOf(3)); check("res12", Integer.valueOf(2)); check("res13", Integer.valueOf(4)); check("res14", Integer.valueOf(3)); check("res15", Integer.valueOf(4)); } public void test_operators_logical(){ doCompile("test_operators_logical"); //TODO: please double check this. check("res1", false); check("res2", false); check("res3", true); check("res4", true); check("res5", false); check("res6", false); check("res7", true); check("res8", false); } public void test_regex(){ doCompile("test_regex"); check("eq0", false); check("eq1", true); check("eq2", false); check("eq3", true); check("eq4", false); check("eq5", true); } public void test_if() { doCompile("test_if"); // if with single statement check("cond1", true); check("res1", true); // if with mutliple statements (block) check("cond2", true); check("res21", true); check("res22", true); // else with single statement check("cond3", false); check("res31", false); check("res32", true); // else with multiple statements (block) check("cond4", false); check("res41", false); check("res42", true); check("res43", true); // if with block, else with block check("cond5", false); check("res51", false); check("res52", false); check("res53", true); check("res54", true); // else-if with single statement check("cond61", false); check("cond62", true); check("res61", false); check("res62", true); // else-if with multiple statements check("cond71", false); check("cond72", true); check("res71", false); check("res72", true); check("res73", true); // if-elseif-else test check("cond81", false); check("cond82", false); check("res81", false); check("res82", false); check("res83", true); // if with single statement + inactive else check("cond9", true); check("res91", true); check("res92", false); // if with multiple statements + inactive else with block check("cond10", true); check("res101", true); check("res102", true); check("res103", false); check("res104", false); // if with condition check("i", 0); check("j", 1); check("res11", true); } public void test_switch() { doCompile("test_switch"); // simple switch check("cond1", 1); check("res11", false); check("res12", true); check("res13", false); // switch, no break check("cond2", 1); check("res21", false); check("res22", true); check("res23", true); // default branch check("cond3", 3); check("res31", false); check("res32", false); check("res33", true); // no default branch => no match check("cond4", 3); check("res41", false); check("res42", false); check("res43", false); // multiple statements in a single case-branch check("cond5", 1); check("res51", false); check("res52", true); check("res53", true); check("res54", false); // single statement shared by several case labels check("cond6", 1); check("res61", false); check("res62", true); check("res63", true); check("res64", false); check("res71", "default case"); check("res72", "null case"); check("res73", "null case"); check("res74", "default case"); } public void test_int_switch(){ doCompile("test_int_switch"); // simple switch check("cond1", 1); check("res11", true); check("res12", false); check("res13", false); // first case is not followed by a break check("cond2", 1); check("res21", true); check("res22", true); check("res23", false); // first and second case have multiple labels check("cond3", 12); check("res31", false); check("res32", true); check("res33", false); // first and second case have multiple labels and no break after first group check("cond4", 11); check("res41", true); check("res42", true); check("res43", false); // default case intermixed with other case labels in the second group check("cond5", 11); check("res51", true); check("res52", true); check("res53", true); // default case intermixed, with break check("cond6", 16); check("res61", false); check("res62", true); check("res63", false); // continue test check("res7", Arrays.asList( /* i=0 */false, false, false, /* i=1 */true, true, false, /* i=2 */true, true, false, /* i=3 */false, true, false, /* i=4 */false, true, false, /* i=5 */false, false, true)); // return test check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3")); } public void test_non_int_switch(){ doCompile("test_non_int_switch"); // simple switch check("cond1", "1"); check("res11", true); check("res12", false); check("res13", false); // first case is not followed by a break check("cond2", "1"); check("res21", true); check("res22", true); check("res23", false); // first and second case have multiple labels check("cond3", "12"); check("res31", false); check("res32", true); check("res33", false); // first and second case have multiple labels and no break after first group check("cond4", "11"); check("res41", true); check("res42", true); check("res43", false); // default case intermixed with other case labels in the second group check("cond5", "11"); check("res51", true); check("res52", true); check("res53", true); // default case intermixed, with break check("cond6", "16"); check("res61", false); check("res62", true); check("res63", false); // continue test check("res7", Arrays.asList( /* i=0 */false, false, false, /* i=1 */true, true, false, /* i=2 */true, true, false, /* i=3 */false, true, false, /* i=4 */false, true, false, /* i=5 */false, false, true)); // return test check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3")); } public void test_while() { doCompile("test_while"); // simple while check("res1", Arrays.asList(0, 1, 2)); // continue check("res2", Arrays.asList(0, 2)); // break check("res3", Arrays.asList(0)); } public void test_do_while() { doCompile("test_do_while"); // simple while check("res1", Arrays.asList(0, 1, 2)); // continue check("res2", Arrays.asList(0, null, 2)); // break check("res3", Arrays.asList(0)); } public void test_for() { doCompile("test_for"); // simple loop check("res1", Arrays.asList(0,1,2)); // continue check("res2", Arrays.asList(0,null,2)); // break check("res3", Arrays.asList(0)); // empty init check("res4", Arrays.asList(0,1,2)); // empty update check("res5", Arrays.asList(0,1,2)); // empty final condition check("res6", Arrays.asList(0,1,2)); // all conditions empty check("res7", Arrays.asList(0,1,2)); } public void test_for1() { //5125: CTL2: "for" cycle is EXTREMELY memory consuming doCompile("test_for1"); checkEquals("counter", "COUNT"); } @SuppressWarnings("unchecked") public void test_foreach() { doCompile("test_foreach"); check("intRes", Arrays.asList(VALUE_VALUE)); check("longRes", Arrays.asList(BORN_MILLISEC_VALUE)); check("doubleRes", Arrays.asList(AGE_VALUE)); check("decimalRes", Arrays.asList(CURRENCY_VALUE)); check("booleanRes", Arrays.asList(FLAG_VALUE)); check("stringRes", Arrays.asList(NAME_VALUE, CITY_VALUE)); check("dateRes", Arrays.asList(BORN_VALUE)); List<?> integerStringMapResTmp = (List<?>) getVariable("integerStringMapRes"); List<String> integerStringMapRes = new ArrayList<String>(integerStringMapResTmp.size()); for (Object o: integerStringMapResTmp) { integerStringMapRes.add(String.valueOf(o)); } List<Integer> stringIntegerMapRes = (List<Integer>) getVariable("stringIntegerMapRes"); List<DataRecord> stringRecordMapRes = (List<DataRecord>) getVariable("stringRecordMapRes"); Collections.sort(integerStringMapRes); Collections.sort(stringIntegerMapRes); assertEquals(Arrays.asList("0", "1", "2", "3", "4"), integerStringMapRes); assertEquals(Arrays.asList(0, 1, 2, 3, 4), stringIntegerMapRes); final int N = 5; assertEquals(N, stringRecordMapRes.size()); int equalRecords = 0; for (int i = 0; i < N; i++) { for (DataRecord r: stringRecordMapRes) { if (Integer.valueOf(i).equals(r.getField("Value").getValue()) && "A string".equals(String.valueOf(r.getField("Name").getValue()))) { equalRecords++; break; } } } assertEquals(N, equalRecords); } public void test_return(){ doCompile("test_return"); check("lhs", Integer.valueOf(1)); check("rhs", Integer.valueOf(2)); check("res", Integer.valueOf(3)); } public void test_return_incorrect() { doCompileExpectError("test_return_incorrect", "Can't convert from 'string' to 'integer'"); } public void test_return_void() { doCompile("test_return_void"); } public void test_overloading() { doCompile("test_overloading"); check("res1", Integer.valueOf(3)); check("res2", "Memento mori"); } public void test_overloading_incorrect() { doCompileExpectErrors("test_overloading_incorrect", Arrays.asList( "Duplicate function 'integer sum(integer, integer)'", "Duplicate function 'integer sum(integer, integer)'")); } //Test case for 4038 public void test_function_parameter_without_type() { doCompileExpectError("test_function_parameter_without_type", "Syntax error on token ')'"); } public void test_duplicate_import() { URL importLoc = getClass().getSuperclass().getResource("test_duplicate_import.ctl"); String expStr = "import '" + importLoc + "';\n"; expStr += "import '" + importLoc + "';\n"; doCompile(expStr, "test_duplicate_import"); } /*TODO: * public void test_invalid_import() { URL importLoc = getClass().getResource("test_duplicate_import.ctl"); String expStr = "import '/a/b/c/d/e/f/g/h/i/j/k/l/m';\n"; expStr += expStr; doCompileExpectError(expStr, "test_invalid_import", Arrays.asList("TODO: Unknown error")); //doCompileExpectError(expStr, "test_duplicate_import", Arrays.asList("TODO: Unknown error")); } */ public void test_built_in_functions(){ doCompile("test_built_in_functions"); check("notNullValue", Integer.valueOf(1)); checkNull("nullValue"); check("isNullRes1", false); check("isNullRes2", true); assertEquals("nvlRes1", getVariable("notNullValue"), getVariable("nvlRes1")); check("nvlRes2", Integer.valueOf(2)); assertEquals("nvl2Res1", getVariable("notNullValue"), getVariable("nvl2Res1")); check("nvl2Res2", Integer.valueOf(2)); check("iifRes1", Integer.valueOf(2)); check("iifRes2", Integer.valueOf(1)); } public void test_local_functions() { // CLO-1246 doCompile("test_local_functions"); } public void test_mapping(){ doCompile("test_mapping"); // simple mappings assertEquals("Name", NAME_VALUE, outputRecords[0].getField("Name").getValue().toString()); assertEquals("Age", AGE_VALUE, outputRecords[0].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[0].getField("City").getValue().toString()); assertEquals("Born", BORN_VALUE, outputRecords[0].getField("Born").getValue()); // * mapping assertTrue(recordEquals(inputRecords[1], outputRecords[1])); check("len", 2); } public void test_mapping_null_values() { doCompile("test_mapping_null_values"); assertTrue(recordEquals(inputRecords[2], outputRecords[0])); } public void test_copyByName() { doCompile("test_copyByName"); assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue()); assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString()); } public void test_copyByName_expect_error(){ try { doCompile("function integer transform(){\n" + "firstInput fi1 = null; firstInput fi2;\n" + "copyByName(fi1, fi2); \n" + "return 0;}","test_copyByName_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "firstInput fi1 = null; firstInput fi2 = null;\n" + "copyByName(fi1, fi2); \n" + "return 0;}","test_copyByName_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_copyByName_assignment() { doCompile("test_copyByName_assignment"); assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue()); assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString()); } public void test_copyByName_assignment1() { doCompile("test_copyByName_assignment1"); assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue()); assertEquals("Age", null, outputRecords[3].getField("Age").getValue()); assertEquals("City", null, outputRecords[3].getField("City").getValue()); } public void test_containerlib_copyByPosition(){ doCompile("test_containerlib_copyByPosition"); assertEquals("Field1", NAME_VALUE, outputRecords[3].getField("Field1").getValue().toString()); assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString()); } public void test_containerlib_copyByPosition_expect_error(){ try { doCompile("function integer transform(){\n" + "firstInput fi1 = null; firstInput fi2; \n" + "copyByPosition(fi1, fi2);\n" + "return 0;}","test_containerlib_copyByPosition_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "firstInput fi1 = null; firstInput fi2 = null; \n" + "copyByPosition(fi1, fi2);\n" + "return 0;}","test_containerlib_copyByPosition_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_sequence(){ doCompile("test_sequence"); check("intRes", Arrays.asList(0,1,2)); check("longRes", Arrays.asList(Long.valueOf(0),Long.valueOf(1),Long.valueOf(2))); check("stringRes", Arrays.asList("0","1","2")); check("intCurrent", Integer.valueOf(2)); check("longCurrent", Long.valueOf(2)); check("stringCurrent", "2"); } //TODO: If this test fails please double check whether the test is correct? public void test_lookup(){ doCompile("test_lookup"); check("alphaResult", Arrays.asList("Andorra la Vella","Andorra la Vella")); check("bravoResult", Arrays.asList("Bruxelles","Bruxelles")); check("charlieResult", Arrays.asList("Chamonix","Chodov","Chomutov","Chamonix","Chodov","Chomutov")); check("countResult", Arrays.asList(3,3)); check("charlieUpdatedCount", 5); check("charlieUpdatedResult", Arrays.asList("Chamonix", "Cheb", "Chodov", "Chomutov", "Chrudim")); check("putResult", true); check("meta", null); check("meta2", null); check("meta3", null); check("meta4", null); check("strRet", "Bratislava"); check("strRet2","Andorra la Vella"); check("intRet", 0); check("intRet2", 1); check("meta7", null); // CLO-1582 check("nonExistingKeyRecord", null); check("nullKeyRecord", null); check("unusedNext", getVariable("unusedNextExpected")); } public void test_lookup_expect_error(){ //CLO-1582 try { doCompile("function integer transform(){string str = lookup(TestLookup).get('Alpha',2).City; return 0;}","test_lookup_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer count = lookup(TestLookup).count('Alpha',1); printErr(count); lookup(TestLookup).next(); string city = lookup(TestLookup).next().City; return 0;}","test_lookup_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){lookupMetadata meta = null; lookup(TestLookup).put(meta); return 0;}","test_lookup_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){lookup(TestLookup).put(null); return 0;}","test_lookup_expect_error"); fail(); } catch (Exception e) { // do nothing } } //------------------------- ContainerLib Tests--------------------- public void test_containerlib_append() { doCompile("test_containerlib_append"); check("appendElem", Integer.valueOf(10)); check("appendList", Arrays.asList(1, 2, 3, 4, 5, 10)); check("stringList", Arrays.asList("horse","is","pretty","scary")); check("stringList2", Arrays.asList("horse", null)); check("stringList3", Arrays.asList("horse", "")); check("integerList1", Arrays.asList(1,2,3,4)); check("integerList2", Arrays.asList(1,2,null)); check("numberList1", Arrays.asList(0.21,1.1,2.2)); check("numberList2", Arrays.asList(1.1,null)); check("longList1", Arrays.asList(1l,2l,3L)); check("longList2", Arrays.asList(9L,null)); check("decList1", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("4.5"),new BigDecimal("6.7"))); check("decList2",Arrays.asList(new BigDecimal("1.1"), null)); } public void test_containerlib_append_expect_error(){ try { doCompile("function integer transform(){string[] listInput = null; append(listInput,'aa'); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte[] listInput = null; append(listInput,str2byte('third', 'utf-8')); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long[] listInput = null; append(listInput,15L); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] listInput = null; append(listInput,12); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal[] listInput = null; append(listInput,12.5d); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number[] listInput = null; append(listInput,12.36); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } } @SuppressWarnings("unchecked") public void test_containerlib_clear() { doCompile("test_containerlib_clear"); assertTrue(((List<Integer>) getVariable("integerList")).isEmpty()); assertTrue(((List<Integer>) getVariable("strList")).isEmpty()); assertTrue(((List<Integer>) getVariable("longList")).isEmpty()); assertTrue(((List<Integer>) getVariable("decList")).isEmpty()); assertTrue(((List<Integer>) getVariable("numList")).isEmpty()); assertTrue(((List<Integer>) getVariable("byteList")).isEmpty()); assertTrue(((List<Integer>) getVariable("dateList")).isEmpty()); assertTrue(((List<Integer>) getVariable("boolList")).isEmpty()); assertTrue(((List<Integer>) getVariable("emptyList")).isEmpty()); assertTrue(((Map<String,Integer>) getVariable("myMap")).isEmpty()); } public void test_container_clear_expect_error(){ try { doCompile("function integer transform(){boolean[] nullList = null; clear(nullList); return 0;}","test_container_clear_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[integer,string] myMap = null; clear(myMap); return 0;}","test_container_clear_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_copy() { doCompile("test_containerlib_copy"); check("copyIntList", Arrays.asList(1, 2, 3, 4, 5)); check("returnedIntList", Arrays.asList(1, 2, 3, 4, 5)); check("copyLongList", Arrays.asList(21L,15L, null, 10L)); check("returnedLongList", Arrays.asList(21l, 15l, null, 10L)); check("copyBoolList", Arrays.asList(false,false,null,true)); check("returnedBoolList", Arrays.asList(false,false,null,true)); Calendar cal = Calendar.getInstance(); cal.set(2006, 10, 12, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2002, 03, 12, 0, 0, 0); cal2.set(Calendar.MILLISECOND, 0); check("copyDateList",Arrays.asList(cal2.getTime(), null, cal.getTime())); check("returnedDateList",Arrays.asList(cal2.getTime(), null, cal.getTime())); check("copyStrList", Arrays.asList("Ashe", "Jax", null, "Rengar")); check("returnedStrList", Arrays.asList("Ashe", "Jax", null, "Rengar")); check("copyNumList", Arrays.asList(12.65d, 458.3d, null, 15.65d)); check("returnedNumList", Arrays.asList(12.65d, 458.3d, null, 15.65d)); check("copyDecList", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("5.9"), null, new BigDecimal("15.3"))); check("returnedDecList", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("5.9"), null, new BigDecimal("15.3"))); Map<String, String> expectedMap = new HashMap<String, String>(); expectedMap.put("a", "a"); expectedMap.put("b", "b"); expectedMap.put("c", "c"); expectedMap.put("d", "d"); check("copyStrMap", expectedMap); check("returnedStrMap", expectedMap); Map<Integer, Integer> intMap = new HashMap<Integer, Integer>(); intMap.put(1,12); intMap.put(2,null); intMap.put(3,15); check("copyIntMap", intMap); check("returnedIntMap", intMap); Map<Long, Long> longMap = new HashMap<Long, Long>(); longMap.put(10L, 453L); longMap.put(11L, null); longMap.put(12L, 54755L); check("copyLongMap", longMap); check("returnedLongMap", longMap); Map<BigDecimal, BigDecimal> decMap = new HashMap<BigDecimal, BigDecimal>(); decMap.put(new BigDecimal("2.2"), new BigDecimal("12.3")); decMap.put(new BigDecimal("2.3"), new BigDecimal("45.6")); check("copyDecMap", decMap); check("returnedDecMap", decMap); Map<Double, Double> doubleMap = new HashMap<Double, Double>(); doubleMap.put(new Double(12.3d), new Double(11.2d)); doubleMap.put(new Double(13.4d), new Double(78.9d)); check("copyNumMap",doubleMap); check("returnedNumMap", doubleMap); List<String> myList = new ArrayList<String>(); check("copyEmptyList", myList); check("returnedEmptyList", myList); assertTrue(((List<String>)(getVariable("copyEmptyList"))).isEmpty()); assertTrue(((List<String>)(getVariable("returnedEmptyList"))).isEmpty()); Map<String, String> emptyMap = new HashMap<String, String>(); check("copyEmptyMap", emptyMap); check("returnedEmptyMap", emptyMap); assertTrue(((HashMap<String,String>)(getVariable("copyEmptyMap"))).isEmpty()); assertTrue(((HashMap<String,String>)(getVariable("returnedEmptyMap"))).isEmpty()); } public void test_containerlib_copy_expect_error(){ try { doCompile("function integer transform(){string[] origList = null; string[] copyList; string[] ret = copy(copyList, origList); return 0;}","test_containerlib_copy_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] origList; string[] copyList = null; string[] ret = copy(copyList, origList); return 0;}","test_containerlib_copy_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string, string] orig = null; map[string, string] copy; map[string, string] ret = copy(copy, orig); return 0;}","test_containerlib_copy_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string, string] orig; map[string, string] copy = null; map[string, string] ret = copy(copy, orig); return 0;}","test_containerlib_copy_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_insert() { doCompile("test_containerlib_insert"); check("copyStrList",Arrays.asList("Elise","Volibear","Garen","Jarvan IV")); check("retStrList",Arrays.asList("Elise","Volibear","Garen","Jarvan IV")); check("copyStrList2", Arrays.asList("Jax", "Aatrox", "Lisandra", "Ashe")); check("retStrList2", Arrays.asList("Jax", "Aatrox", "Lisandra", "Ashe")); Calendar cal = Calendar.getInstance(); cal.set(2009, 10, 12, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal1 = Calendar.getInstance(); cal1.set(2008, 2, 7, 0, 0, 0); cal1.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2003, 01, 1, 0, 0, 0); cal2.set(Calendar.MILLISECOND, 0); check("copyDateList", Arrays.asList(cal1.getTime(),cal.getTime())); check("retDateList", Arrays.asList(cal1.getTime(),cal.getTime())); check("copyDateList2", Arrays.asList(cal2.getTime(),cal1.getTime(),cal.getTime())); check("retDateList2", Arrays.asList(cal2.getTime(),cal1.getTime(),cal.getTime())); check("copyIntList", Arrays.asList(1,2,3,12,4,5,6,7)); check("retIntList", Arrays.asList(1,2,3,12,4,5,6,7)); check("copyLongList", Arrays.asList(14L,15l,16l,17l)); check("retLongList", Arrays.asList(14L,15l,16l,17l)); check("copyLongList2", Arrays.asList(20L,21L,22L,23l)); check("retLongList2", Arrays.asList(20L,21L,22L,23l)); check("copyNumList", Arrays.asList(12.3d,11.1d,15.4d)); check("retNumList", Arrays.asList(12.3d,11.1d,15.4d)); check("copyNumList2", Arrays.asList(22.2d,44.4d,55.5d,33.3d)); check("retNumList2", Arrays.asList(22.2d,44.4d,55.5d,33.3d)); check("copyDecList", Arrays.asList(new BigDecimal("11.1"), new BigDecimal("22.2"), new BigDecimal("33.3"))); check("retDecList", Arrays.asList(new BigDecimal("11.1"), new BigDecimal("22.2"), new BigDecimal("33.3"))); check("copyDecList2",Arrays.asList(new BigDecimal("3.3"), new BigDecimal("4.4"), new BigDecimal("1.1"), new BigDecimal("2.2"))); check("retDecList2",Arrays.asList(new BigDecimal("3.3"), new BigDecimal("4.4"), new BigDecimal("1.1"), new BigDecimal("2.2"))); check("copyEmpty", Arrays.asList(11)); check("retEmpty", Arrays.asList(11)); check("copyEmpty2", Arrays.asList(12,13)); check("retEmpty2", Arrays.asList(12,13)); check("copyEmpty3", Arrays.asList()); check("retEmpty3", Arrays.asList()); } public void test_containerlib_insert_expect_error(){ try { doCompile("function integer transform(){integer[] tmp = null; integer[] ret = insert(tmp,0,12); return 0;}","test_containerlib_insert_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] tmp; integer[] toAdd = null; integer[] ret = insert(tmp,0,toAdd); return 0;}","test_containerlib_insert_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] tmp = [11,12]; integer[] ret = insert(tmp,-1,12); return 0;}","test_containerlib_insert_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] tmp = [11,12]; integer[] ret = insert(tmp,10,12); return 0;}","test_containerlib_insert_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_isEmpty() { doCompile("test_containerlib_isEmpty"); check("emptyMap", true); check("emptyMap1", true); check("fullMap", false); check("fullMap1", false); check("emptyList", true); check("emptyList1", true); check("fullList", false); check("fullList1", false); } public void test_containerlib_isEmpty_expect_error(){ try { doCompile("function integer transform(){integer[] i = null; boolean boo = i.isEmpty(); return 0;}","test_containerlib_isEmpty_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string, string] m = null; boolean boo = m.isEmpty(); return 0;}","test_containerlib_isEmpty_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_length(){ doCompile("test_containerlib_length"); check("lengthByte", 18); check("lengthByte2", 18); check("recordLength", 9); check("recordLength2", 9); check("listLength", 3); check("listLength2", 3); check("emptyListLength", 0); check("emptyListLength2", 0); check("emptyMapLength", 0); check("emptyMapLength2", 0); check("nullLength1", 0); check("nullLength2", 0); check("nullLength3", 0); check("nullLength4", 0); check("nullLength5", 0); check("nullLength6", 0); } public void test_containerlib_poll() throws UnsupportedEncodingException { doCompile("test_containerlib_poll"); check("intElem", Integer.valueOf(1)); check("intElem1", 2); check("intList", Arrays.asList(3, 4, 5)); check("strElem", "Zyra"); check("strElem2", "Tresh"); check("strList", Arrays.asList("Janna", "Wu Kong")); Calendar cal = Calendar.getInstance(); cal.set(2002, 10, 12, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); check("dateElem", cal.getTime()); cal.clear(); cal.set(2003,5,12,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("dateElem2", cal.getTime()); cal.clear(); cal.set(2006,9,15,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal.getTime())); checkArray("byteElem", "Maoki".getBytes("UTF-8")); checkArray("byteElem2", "Nasus".getBytes("UTF-8")); check("longElem", 12L); check("longElem2", 15L); check("longList", Arrays.asList(16L,23L)); check("numElem", 23.6d); check("numElem2", 15.9d); check("numList", Arrays.asList(78.8d, 57.2d)); check("decElem", new BigDecimal("12.3")); check("decElem2", new BigDecimal("23.4")); check("decList", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6"))); check("emptyElem", null); check("emptyElem2", null); check("emptyList", Arrays.asList()); } public void test_containerlib_poll_expect_error(){ try { doCompile("function integer transform(){integer[] arr = null; integer i = poll(arr); return 0;}","test_containerlib_poll_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] arr = null; integer i = arr.poll(); return 0;}","test_containerlib_poll_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_pop() { doCompile("test_containerlib_pop"); check("intElem", 5); check("intElem2", 4); check("intList", Arrays.asList(1, 2, 3)); check("longElem", 14L); check("longElem2", 13L); check("longList", Arrays.asList(11L,12L)); check("numElem", 11.5d); check("numElem2", 11.4d); check("numList", Arrays.asList(11.2d,11.3d)); check("decElem", new BigDecimal("22.5")); check("decElem2", new BigDecimal("22.4")); check("decList", Arrays.asList(new BigDecimal("22.2"), new BigDecimal("22.3"))); Calendar cal = Calendar.getInstance(); cal.set(2005, 8, 24, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); check("dateElem",cal.getTime()); cal.clear(); cal.set(2001, 6, 13, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); check("dateElem2", cal.getTime()); cal.clear(); cal.set(2010, 5, 11, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2011,3,3,0,0,0); cal2.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal.getTime(),cal2.getTime())); check("strElem", "Ezrael"); check("strElem2", null); check("strList", Arrays.asList("Kha-Zix", "Xerath")); check("emptyElem", null); check("emptyElem2", null); } public void test_containerlib_pop_expect_error(){ try { doCompile("function integer transform(){string[] arr = null; string str = pop(arr); return 0;}","test_containerlib_pop_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] arr = null; string str = arr.pop(); return 0;}","test_containerlib_pop_expect_error"); fail(); } catch (Exception e) { // do nothing } } @SuppressWarnings("unchecked") public void test_containerlib_push() { doCompile("test_containerlib_push"); check("intCopy", Arrays.asList(1, 2, 3)); check("intRet", Arrays.asList(1, 2, 3)); check("longCopy", Arrays.asList(12l,13l,14l)); check("longRet", Arrays.asList(12l,13l,14l)); check("numCopy", Arrays.asList(11.1d,11.2d,11.3d)); check("numRet", Arrays.asList(11.1d,11.2d,11.3d)); check("decCopy", Arrays.asList(new BigDecimal("12.2"), new BigDecimal("12.3"), new BigDecimal("12.4"))); check("decRet", Arrays.asList(new BigDecimal("12.2"), new BigDecimal("12.3"), new BigDecimal("12.4"))); check("strCopy", Arrays.asList("Fiora", "Nunu", "Amumu")); check("strRet", Arrays.asList("Fiora", "Nunu", "Amumu")); Calendar cal = Calendar.getInstance(); cal.set(2001, 5, 9, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal1 = Calendar.getInstance(); cal1.set(2005, 5, 9, 0, 0, 0); cal1.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2011, 5, 9, 0, 0, 0); cal2.set(Calendar.MILLISECOND, 0); check("dateCopy", Arrays.asList(cal.getTime(),cal1.getTime(),cal2.getTime())); check("dateRet", Arrays.asList(cal.getTime(),cal1.getTime(),cal2.getTime())); String str = null; check("emptyCopy", Arrays.asList(str)); check("emptyRet", Arrays.asList(str)); // there is hardly any way to get an instance of DataRecord // hence we just check if the list has correct size // and if its elements have correct metadata List<DataRecord> recordList = (List<DataRecord>) getVariable("recordList"); List<DataRecordMetadata> mdList = Arrays.asList( graph.getDataRecordMetadata(OUTPUT_1), graph.getDataRecordMetadata(INPUT_2), graph.getDataRecordMetadata(INPUT_1) ); assertEquals(mdList.size(), recordList.size()); for (int i = 0; i < mdList.size(); i++) { assertEquals(mdList.get(i), recordList.get(i).getMetadata()); } } public void test_containerlib_push_expect_error(){ try { doCompile("function integer transform(){string[] str = null; str.push('a'); return 0;}","test_containerlib_push_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] str = null; push(str, 'a'); return 0;}","test_containerlib_push_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_remove() { doCompile("test_containerlib_remove"); check("intElem", 2); check("intList", Arrays.asList(1, 3, 4, 5)); check("longElem", 13L); check("longList", Arrays.asList(11l,12l,14l)); check("numElem", 11.3d); check("numList", Arrays.asList(11.1d,11.2d,11.4d)); check("decElem", new BigDecimal("11.3")); check("decList", Arrays.asList(new BigDecimal("11.1"),new BigDecimal("11.2"),new BigDecimal("11.4"))); Calendar cal = Calendar.getInstance(); cal.set(2002,10,13,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("dateElem", cal.getTime()); cal.clear(); cal.set(2001,10,13,0,0,0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2003,10,13,0,0,0); cal2.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal.getTime(), cal2.getTime())); check("strElem", "Shivana"); check("strList", Arrays.asList("Annie","Lux")); } public void test_containerlib_remove_expect_error(){ try { doCompile("function integer transform(){string[] strList; string str = remove(strList,0); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] strList; string str = strList.remove(0); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] strList = ['Teemo']; string str = remove(strList,5); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] strList = ['Teemo']; string str = remove(strList,-1); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] strList = null; string str = remove(strList,0); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_reverse_expect_error(){ try { doCompile("function integer transform(){long[] longList = null; reverse(longList); return 0;}","test_containerlib_reverse_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){reverse(null); return 0;}","test_containerlib_reverse_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long[] longList = null; long[] reversed = longList.reverse(); return 0;}","test_containerlib_reverse_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_reverse() { doCompile("test_containerlib_reverse"); check("intList", Arrays.asList(5, 4, 3, 2, 1)); check("intList2", Arrays.asList(5, 4, 3, 2, 1)); check("longList", Arrays.asList(14l,13l,12l,11l)); check("longList2", Arrays.asList(14l,13l,12l,11l)); check("numList", Arrays.asList(1.3d,1.2d,1.1d)); check("numList2", Arrays.asList(1.3d,1.2d,1.1d)); check("decList", Arrays.asList(new BigDecimal("1.3"),new BigDecimal("1.2"),new BigDecimal("1.1"))); check("decList2", Arrays.asList(new BigDecimal("1.3"),new BigDecimal("1.2"),new BigDecimal("1.1"))); check("strList", Arrays.asList(null,"Lulu","Kog Maw")); check("strList2", Arrays.asList(null,"Lulu","Kog Maw")); Calendar cal = Calendar.getInstance(); cal.set(2001,2,1,0,0,0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2002,2,1,0,0,0); cal2.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal2.getTime(),cal.getTime())); check("dateList2", Arrays.asList(cal2.getTime(),cal.getTime())); } public void test_containerlib_sort() { doCompile("test_containerlib_sort"); check("intList", Arrays.asList(1, 1, 2, 3, 5)); check("intList2", Arrays.asList(1, 1, 2, 3, 5)); check("longList", Arrays.asList(21l,22l,23l,24l)); check("longList2", Arrays.asList(21l,22l,23l,24l)); check("decList", Arrays.asList(new BigDecimal("1.1"),new BigDecimal("1.2"),new BigDecimal("1.3"),new BigDecimal("1.4"))); check("decList2", Arrays.asList(new BigDecimal("1.1"),new BigDecimal("1.2"),new BigDecimal("1.3"),new BigDecimal("1.4"))); check("numList", Arrays.asList(1.1d,1.2d,1.3d,1.4d)); check("numList2", Arrays.asList(1.1d,1.2d,1.3d,1.4d)); Calendar cal = Calendar.getInstance(); cal.set(2002,5,12,0,0,0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2003,5,12,0,0,0); cal2.set(Calendar.MILLISECOND, 0); Calendar cal3 = Calendar.getInstance(); cal3.set(2004,5,12,0,0,0); cal3.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal.getTime(),cal2.getTime(),cal3.getTime())); check("dateList2", Arrays.asList(cal.getTime(),cal2.getTime(),cal3.getTime())); check("strList", Arrays.asList("","Alistar", "Nocturne", "Soraka")); check("strList2", Arrays.asList("","Alistar", "Nocturne", "Soraka")); check("emptyList", Arrays.asList()); check("emptyList2", Arrays.asList()); check("retNull1", Arrays.asList("Kennen", "Renector", null, null)); check("retNull2", Arrays.asList(false, true, true, null, null, null)); cal.clear(); cal.set(2001,0,20,0,0,0); cal.set(Calendar.MILLISECOND, 0); cal2.clear(); cal2.set(2003,4,12,0,0,0); cal2.set(Calendar.MILLISECOND, 0); check("retNull3", Arrays.asList(cal.getTime(), cal2.getTime(), null, null)); check("retNull4", Arrays.asList(1,8,10,12,null,null,null)); check("retNull5", Arrays.asList(1l, 12l, 15l, null, null, null)); check("retNull6", Arrays.asList(12.1d, 12.3d, 12.4d, null, null)); check("retNull7", Arrays.asList(new BigDecimal("11"), new BigDecimal("11.1"), new BigDecimal("11.2"), null, null, null)); } public void test_containerlib_sort_expect_error(){ try { doCompile("function integer transform(){string[] strList = null; sort(strList); return 0;}","test_containerlib_sort_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_containsAll() { doCompile("test_containerlib_containsAll"); check("results", Arrays.asList(true, false, true, false, true, true, true, false, true, true, false)); check("test1", true); check("test2", true); check("test3", true); check("test4", false); check("test5", true); check("test6", false); check("test7", true); check("test8", false); check("test9", true); check("test10", false); check("test11", true); check("test12", false); check("test13", false); check("test14", true); check("test15", false); check("test16", false); } public void test_containerlib_containsAll_expect_error(){ try { doCompile("function integer transform(){integer[] intList = null; boolean b =intList.containsAll([1]); return 0;}","test_containerlib_containsAll_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] intList; boolean b =intList.containsAll(null); return 0;}","test_containerlib_containsAll_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer[] intList; integer[] intList2 = null;" + "boolean b =intList.containsAll(intList2); return 0;}","test_containerlib_containsAll_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer[] intList = null; integer[] intList2 = null;" + "boolean b =intList.containsAll(intList2); return 0;}","test_containerlib_containsAll_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_containsKey() { doCompile("test_containerlib_containsKey"); check("results", Arrays.asList(false, true, false, true, false, true)); check("test1", true); check("test2", false); check("test3", true); check("test4", false); check("test5", true); check("test6", false); check("test7", true); check("test8", true); check("test9", true); check("test10", false); check("test11", true); check("test12", true); check("test13", false); check("test14", true); check("test15", true); check("test16", false); check("test17", true); check("test18", true); check("test19", false); check("test20", false); } public void test_containerlib_containsKey_expect_error(){ try { doCompile("function integer transform(){map[string, integer] emptyMap = null; boolean b = emptyMap.containsKey('a'); return 0;}","test_containerlib_containsKey_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_containsValue() { doCompile("test_containerlib_containsValue"); check("results", Arrays.asList(true, false, false, true, false, false, true, false)); check("test1", true); check("test2", true); check("test3", false); check("test4", true); check("test5", true); check("test6", false); check("test7", false); check("test8", true); check("test9", true); check("test10", false); check("test11", true); check("test12", true); check("test13", false); check("test14", true); check("test15", true); check("test16", false); check("test17", true); check("test18", true); check("test19", false); check("test20", true); check("test21", true); check("test22", false); check("test23", true); check("test24", true); check("test25", false); check("test26", false); } public void test_convertlib_containsValue_expect_error(){ try { doCompile("function integer transform(){map[integer, long] nullMap = null; boolean b = nullMap.containsValue(18L); return 0;}","test_convertlib_containsValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_getKeys() { doCompile("test_containerlib_getKeys"); check("stringList", Arrays.asList("a","b")); check("stringList2", Arrays.asList("a","b")); check("integerList", Arrays.asList(5,7,2)); check("integerList2", Arrays.asList(5,7,2)); List<Date> list = new ArrayList<Date>(); Calendar cal = Calendar.getInstance(); cal.set(2008, 10, 12, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2001, 5, 28, 0, 0, 0); cal2.set(Calendar.MILLISECOND, 0); list.add(cal.getTime()); list.add(cal2.getTime()); check("dateList", list); check("dateList2", list); check("longList", Arrays.asList(14L, 45L)); check("longList2", Arrays.asList(14L, 45L)); check("numList", Arrays.asList(12.3d, 13.4d)); check("numList2", Arrays.asList(12.3d, 13.4d)); check("decList", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6"))); check("decList2", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6"))); check("emptyList", Arrays.asList()); check("emptyList2", Arrays.asList()); } public void test_containerlib_getKeys_expect_error(){ try { doCompile("function integer transform(){map[string,string] strMap = null; string[] str = strMap.getKeys(); return 0;}","test_containerlib_getKeys_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string,string] strMap = null; string[] str = getKeys(strMap); return 0;}","test_containerlib_getKeys_expect_error"); fail(); } catch (Exception e) { // do nothing } } //---------------------- StringLib Tests ------------------------ public void test_stringlib_cache() { doCompile("test_stringlib_cache"); check("rep1", "The cat says meow. All cats say meow."); check("rep2", "The cat says meow. All cats say meow."); check("rep3", "The cat says meow. All cats say meow."); check("find1", Arrays.asList("to", "to", "to", "tro", "to")); check("find2", Arrays.asList("to", "to", "to", "tro", "to")); check("find3", Arrays.asList("to", "to", "to", "tro", "to")); check("split1", Arrays.asList("one", "two", "three", "four", "five")); check("split2", Arrays.asList("one", "two", "three", "four", "five")); check("split3", Arrays.asList("one", "two", "three", "four", "five")); check("chop01", "ting soming choping function"); check("chop02", "ting soming choping function"); check("chop03", "ting soming choping function"); check("chop11", "testing end of lines cutting"); check("chop12", "testing end of lines cutting"); } public void test_stringlib_charAt() { doCompile("test_stringlib_charAt"); String input = "The QUICk !!$ broWn fox juMPS over the lazy DOG "; String[] expected = new String[input.length()]; for (int i = 0; i < expected.length; i++) { expected[i] = String.valueOf(input.charAt(i)); } check("chars", Arrays.asList(expected)); } public void test_stringlib_charAt_error(){ //test: attempt to access char at position, which is out of bounds -> upper bound try { doCompile("string test;function integer transform(){test = charAt('milk', 7);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } //test: attempt to access char at position, which is out of bounds -> lower bound try { doCompile("string test;function integer transform(){test = charAt('milk', -1);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } //test: argument for position is null try { doCompile("string test; integer i = null; function integer transform(){test = charAt('milk', i);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } //test: input is null try { doCompile("string test;function integer transform(){test = charAt(null, 1);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } //test: input is empty string try { doCompile("string test;function integer transform(){test = charAt('', 1);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_concat() { doCompile("test_stringlib_concat"); final SimpleDateFormat format = new SimpleDateFormat(); format.applyPattern("yyyy MMM dd"); check("concat", ""); check("concat1", "ello hi ELLO 2,today is " + format.format(new Date())); check("concat2", ""); check("concat3", "clover"); check("test_null1", "null"); check("test_null2", "null"); check("test_null3","skynullisnullblue"); } public void test_stringlib_countChar() { doCompile("test_stringlib_countChar"); check("charCount", 3); check("count2", 0); } public void test_stringlib_countChar_emptychar() { // test: attempt to count empty chars in string. try { doCompile("integer charCount;function integer transform() {charCount = countChar('aaa','');return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } // test: attempt to count empty chars in empty string. try { doCompile("integer charCount;function integer transform() {charCount = countChar('','');return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } //test: null input - test 1 try { doCompile("integer charCount;function integer transform() {charCount = countChar(null,'a');return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } //test: null input - test 2 try { doCompile("integer charCount;function integer transform() {charCount = countChar(null,'');return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } //test: null input - test 3 try { doCompile("integer charCount;function integer transform() {charCount = countChar(null, null);return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_cut() { doCompile("test_stringlib_cut"); check("cutInput", Arrays.asList("a", "1edf", "h3ijk")); } public void test_string_cut_expect_error() { // test: Attempt to cut substring from position after the end of original string. E.g. string is 6 char long and // user attempt to cut out after position 8. try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[28,3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } // test: Attempt to cut substring longer then possible. E.g. string is 6 characters long and user cuts from // position // 4 substring 4 characters long try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,8]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } // test: Attempt to cut a substring with negative length try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,-3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } // test: Attempt to cut substring from negative position. E.g cut([-3,3]). try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[-3,3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: input is empty string try { doCompile("string input;string[] cutInput;function integer transform() {input = '';cutInput = cut(input,[0,3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: second arg is null try { doCompile("string input;string[] cutInput;function integer transform() {input = 'aaaa';cutInput = cut(input,null);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: input is null try { doCompile("string input;string[] cutInput;function integer transform() {input = null;cutInput = cut(input,[5,11]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_editDistance() { doCompile("test_stringlib_editDistance"); check("dist", 1); check("dist1", 1); check("dist2", 0); check("dist5", 1); check("dist3", 1); check("dist4", 0); check("dist6", 4); check("dist7", 5); check("dist8", 0); check("dist9", 0); } public void test_stringlib_editDistance_expect_error(){ //test: input - empty string - first arg try { doCompile("integer test;function integer transform() {test = editDistance('','mark');return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input - null - first arg try { doCompile("integer test;function integer transform() {test = editDistance(null,'mark');return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input- empty string - second arg try { doCompile("integer test;function integer transform() {test = editDistance('mark','');return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input - null - second argument try { doCompile("integer test;function integer transform() {test = editDistance('mark',null);return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input - both empty try { doCompile("integer test;function integer transform() {test = editDistance('','');return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input - both null try { doCompile("integer test;function integer transform() {test = editDistance(null,null);return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } } public void test_stringlib_find() { doCompile("test_stringlib_find"); check("findList", Arrays.asList("The quick br", "wn f", "x jumps ", "ver the lazy d", "g")); check("findList2", Arrays.asList("mark.twain")); check("findList3", Arrays.asList()); check("findList4", Arrays.asList("", "", "", "", "")); check("findList5", Arrays.asList("twain")); check("findList6", Arrays.asList("")); } public void test_stringlib_find_expect_error() { //test: regexp group number higher then count of regexp groups try { doCompile("string[] findList;function integer transform() {findList = find('[email protected]','(^[a-z]*).([a-z]*)',5); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: negative regexp group number try { doCompile("string[] findList;function integer transform() {findList = find('[email protected]','(^[a-z]*).([a-z]*)',-1); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: arg1 null input try { doCompile("string[] findList;function integer transform() {findList = find(null,'(^[a-z]*).([a-z]*)'); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: arg2 null input - test1 try { doCompile("string[] findList;function integer transform() {findList = find('[email protected]',null); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: arg2 null input - test2 try { doCompile("string[] findList;function integer transform() {findList = find('',null); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: arg1 and arg2 null input try { doCompile("string[] findList;function integer transform() {findList = find(null,null); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } } public void test_stringlib_join() { doCompile("test_stringlib_join"); //check("joinedString", "Bagr,3,3.5641,-87L,CTL2"); check("joinedString1", "80=5455.987\"-5=5455.987\"3=0.1"); check("joinedString2", "5.0♫54.65♫67.0♫231.0"); //check("joinedString3", "5☺54☺65☺67☺231☺80=5455.987☺-5=5455.987☺3=0.1☺CTL2☺42"); check("test_empty1", "abc"); check("test_empty2", ""); check("test_empty3"," "); check("test_empty4","anullb"); check("test_empty5","80=5455.987-5=5455.9873=0.1"); check("test_empty6","80=5455.987 -5=5455.987 3=0.1"); check("test_null1","abc"); check("test_null2",""); check("test_null3","anullb"); check("test_null4","80=5455.987-5=5455.9873=0.1"); //CLO-1210 check("test_empty7","a=xb=nullc=z"); check("test_empty8","a=x b=null c=z"); check("test_empty9","null=xeco=storm"); check("test_empty10","null=x eco=storm"); check("test_null5","a=xb=nullc=z"); check("test_null6","null=xeco=storm"); } public void test_stringlib_join_expect_error(){ // CLO-1567 - join("", null) is ambiguous // try { // doCompile("function integer transform(){string s = join(';',null);return 0;}","test_stringlib_join_expect_error"); // fail(); // } catch (Exception e) { // // do nothing // } try { doCompile("function integer transform(){string[] tmp = null; string s = join(';',tmp);return 0;}","test_stringlib_join_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string,string] a = null; string s = join(';',a);return 0;}","test_stringlib_join_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_left() { // CLO-1193 doCompile("test_stringlib_left"); check("test1", "aa"); check("test2", "aaa"); check("test3", ""); check("test4", null); check("test5", "abc"); check("test6", "ab "); check("test7", " "); check("test8", null); check("test9", "abc"); check("test10", "abc"); check("test11", ""); check("test12", null); check("test13", null); check("test14", ""); check("test15", ""); } public void test_stringlib_left_expect_error(){ try { doCompile("function integer transform(){string s = left('Lux', -7, false); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = left('Darius', -7, true); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = left('Darius', null, true); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer int = null; string s = left('Darius', int, true); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){boolean b = null; string s = left('Darius', 9, b); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = left('Darius', 7, null); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_length() { doCompile("test_stringlib_length"); check("lenght1", new BigDecimal(50)); check("stringLength", 8); check("length_empty", 0); check("length_null1", 0); } public void test_stringlib_lowerCase() { doCompile("test_stringlib_lowerCase"); check("lower", "the quick !!$ brown fox jumps over the lazy dog bagr "); check("lower_empty", ""); check("lower_null", null); } public void test_stringlib_matches() { doCompile("test_stringlib_matches"); check("matches1", true); check("matches2", true); check("matches3", false); check("matches4", true); check("matches5", false); check("matches6", false); check("matches7", false); check("matches8", false); check("matches9", true); check("matches10", true); } public void test_stringlib_matches_expect_error(){ //test: regexp param null - test 1 try { doCompile("boolean test; function integer transform(){test = matches('aaa', null); return 0;}","test_stringlib_matches_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp param null - test 2 try { doCompile("boolean test; function integer transform(){test = matches('', null); return 0;}","test_stringlib_matches_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp param null - test 3 try { doCompile("boolean test; function integer transform(){test = matches(null, null); return 0;}","test_stringlib_matches_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_matchGroups() { doCompile("test_stringlib_matchGroups"); check("result1", null); check("result2", Arrays.asList( //"(([^:]*)([:])([\\(]))(.*)(\\))(((#)(.*))|($))" "zip:(zip:(/path/name?.zip)#innerfolder/file.zip)#innermostfolder?/filename*.txt", "zip:(", "zip", ":", "(", "zip:(/path/name?.zip)#innerfolder/file.zip", ")", "#innermostfolder?/filename*.txt", "#innermostfolder?/filename*.txt", "#", "innermostfolder?/filename*.txt", null ) ); check("result3", null); check("test_empty1", null); check("test_empty2", Arrays.asList("")); check("test_null1", null); check("test_null2", null); } public void test_stringlib_matchGroups_expect_error(){ //test: regexp is null - test 1 try { doCompile("string[] test; function integer transform(){test = matchGroups('eat all the cookies',null); return 0;}","test_stringlib_matchGroups_expect_error"); } catch (Exception e) { // do nothing } //test: regexp is null - test 2 try { doCompile("string[] test; function integer transform(){test = matchGroups('',null); return 0;}","test_stringlib_matchGroups_expect_error"); } catch (Exception e) { // do nothing } //test: regexp is null - test 3 try { doCompile("string[] test; function integer transform(){test = matchGroups(null,null); return 0;}","test_stringlib_matchGroups_expect_error"); } catch (Exception e) { // do nothing } } public void test_stringlib_matchGroups_unmodifiable() { try { doCompile("test_stringlib_matchGroups_unmodifiable"); fail(); } catch (RuntimeException re) { }; } public void test_stringlib_metaphone() { doCompile("test_stringlib_metaphone"); check("metaphone1", "XRS"); check("metaphone2", "KWNTLN"); check("metaphone3", "KWNT"); check("metaphone4", ""); check("metaphone5", ""); check("test_empty1", ""); check("test_empty2", ""); check("test_null1", null); check("test_null2", null); } public void test_stringlib_nysiis() { doCompile("test_stringlib_nysiis"); check("nysiis1", "CAP"); check("nysiis2", "CAP"); check("nysiis3", "1234"); check("nysiis4", "C2 PRADACTAN"); check("nysiis_empty", ""); check("nysiis_null", null); } public void test_stringlib_replace() { doCompile("test_stringlib_replace"); final SimpleDateFormat format = new SimpleDateFormat(); format.applyPattern("yyyy MMM dd"); check("rep", format.format(new Date()).replaceAll("[lL]", "t")); check("rep1", "The cat says meow. All cats say meow."); check("rep2", "intruders must die"); check("test_empty1", "a"); check("test_empty2", ""); check("test_null", null); check("test_null2",""); check("test_null3","bbb"); check("test_null4",null); } public void test_stringlib_replace_expect_error(){ //test: regexp null - test1 try { doCompile("string test; function integer transform(){test = replace('a b',null,'b'); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp null - test2 try { doCompile("string test; function integer transform(){test = replace('',null,'b'); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp null - test3 try { doCompile("string test; function integer transform(){test = replace(null,null,'b'); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: arg3 null - test1 try { doCompile("string test; function integer transform(){test = replace('a b','a+',null); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } // //test: arg3 null - test2 // try { // doCompile("string test; function integer transform(){test = replace('','a+',null); return 0;}","test_stringlib_replace_expect_error"); // fail(); // } catch (Exception e) { // // do nothing // } // //test: arg3 null - test3 // try { // doCompile("string test; function integer transform(){test = replace(null,'a+',null); return 0;}","test_stringlib_replace_expect_error"); // fail(); // } catch (Exception e) { // // do nothing // } //test: regexp and arg3 null - test1 try { doCompile("string test; function integer transform(){test = replace('a b',null,null); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp and arg3 null - test1 try { doCompile("string test; function integer transform(){test = replace(null,null,null); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_right() { doCompile("test_stringlib_right"); check("righ", "y dog"); check("rightNotPadded", "y dog"); check("rightPadded", "y dog"); check("padded", " y dog"); check("notPadded", "y dog"); check("short", "Dog"); check("shortNotPadded", "Dog"); check("shortPadded", " Dog"); check("simple", "milk"); check("test_null1", null); check("test_null2", null); check("test_null3", " "); check("test_empty1", ""); check("test_empty2", ""); check("test_empty3"," "); } public void test_stringlib_soundex() { doCompile("test_stringlib_soundex"); check("soundex1", "W630"); check("soundex2", "W643"); check("test_null", null); check("test_empty", ""); } public void test_stringlib_split() { doCompile("test_stringlib_split"); check("split1", Arrays.asList("The quick br", "wn f", "", " jumps " , "ver the lazy d", "g")); check("test_empty", Arrays.asList("")); check("test_empty2", Arrays.asList("","a","a")); List<String> tmp = new ArrayList<String>(); tmp.add(null); check("test_null", tmp); } public void test_stringlib_split_expect_error(){ //test: regexp null - test1 try { doCompile("function integer transform(){string[] s = split('aaa',null); return 0;}","test_stringlib_split_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp null - test2 try { doCompile("function integer transform(){string[] s = split('',null); return 0;}","test_stringlib_split_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp null - test3 try { doCompile("function integer transform(){string[] s = split(null,null); return 0;}","test_stringlib_split_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_substring() { doCompile("test_stringlib_substring"); check("subs", "UICk "); check("test1", ""); check("test_empty", ""); } public void test_stringlib_substring_expect_error(){ try { doCompile("function integer transform(){string test = substring('arabela',4,19);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('arabela',15,3);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('arabela',2,-3);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('arabela',-5,7);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('',0,7);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('',7,7);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring(null,0,0);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring(null,0,4);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring(null,1,4);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_trim() { doCompile("test_stringlib_trim"); check("trim1", "im The QUICk !!$ broWn fox juMPS over the lazy DOG"); check("trim_empty", ""); check("trim_null", null); } public void test_stringlib_upperCase() { doCompile("test_stringlib_upperCase"); check("upper", "THE QUICK !!$ BROWN FOX JUMPS OVER THE LAZY DOG BAGR "); check("test_empty", ""); check("test_null", null); } public void test_stringlib_isFormat() { doCompile("test_stringlib_isFormat"); check("test", "test"); check("isBlank", Boolean.FALSE); check("blank", ""); checkNull("nullValue"); check("isBlank1", true); check("isBlank2", true); check("isAscii1", true); check("isAscii2", false); check("isAscii3", true); check("isAscii4", true); check("isNumber", false); check("isNumber1", false); check("isNumber2", true); check("isNumber3", true); check("isNumber4", false); check("isNumber5", true); check("isNumber6", true); check("isNumber7", false); check("isNumber8", false); check("isInteger", false); check("isInteger1", false); check("isInteger2", false); check("isInteger3", true); check("isInteger4", false); check("isInteger5", false); check("isLong", true); check("isLong1", false); check("isLong2", false); check("isLong3", false); check("isLong4", false); check("isDate", true); check("isDate1", false); // "kk" allows hour to be 1-24 (as opposed to HH allowing hour to be 0-23) check("isDate2", true); check("isDate3", true); check("isDate4", false); check("isDate5", true); check("isDate6", true); check("isDate7", false); // illegal month: 15 check("isDate9", false); check("isDate10", false); check("isDate11", false); check("isDate12", true); check("isDate13", false); // 24 is an illegal value for pattern HH (it allows only 0-23) check("isDate14", false); // empty string: invalid check("isDate15", false); check("isDate16", false); check("isDate17", true); check("isDate18", true); check("isDate19", false); check("isDate20", false); check("isDate21", false); // CLO-1190 check("isDate22", true); check("isDate23", false); check("isDate24", true); check("isDate25", false); check("isDate26", true); check("isDate27", true); } public void test_stringlib_empty_strings() { String[] expressions = new String[] { "isInteger(?)", "isNumber(?)", "isLong(?)", "isAscii(?)", "isBlank(?)", "isDate(?, \"yyyy\")", "isUrl(?)", "string x = ?; length(x)", "lowerCase(?)", "matches(?, \"\")", "NYSIIS(?)", "removeBlankSpace(?)", "removeDiacritic(?)", "removeNonAscii(?)", "removeNonPrintable(?)", "replace(?, \"a\", \"a\")", "translate(?, \"ab\", \"cd\")", "trim(?)", "upperCase(?)", "chop(?)", "concat(?)", "getAlphanumericChars(?)", }; StringBuilder sb = new StringBuilder(); for (String expr : expressions) { String emptyString = expr.replace("?", "\"\""); boolean crashesEmpty = test_expression_crashes(emptyString); assertFalse("Function " + emptyString + " crashed", crashesEmpty); String nullString = expr.replace("?", "null"); boolean crashesNull = test_expression_crashes(nullString); sb.append(String.format("|%20s|%5s|%5s|%n", expr, crashesEmpty ? "CRASH" : "ok", crashesNull ? "CRASH" : "ok")); } System.out.println(sb.toString()); } private boolean test_expression_crashes(String expr) { String expStr = "function integer transform() { " + expr + "; return 0; }"; try { doCompile(expStr, "test_stringlib_empty_null_strings"); return false; } catch (RuntimeException e) { return true; } } public void test_stringlib_removeBlankSpace() { String expStr = "string r1;\n" + "string str_empty;\n" + "string str_null;\n" + "function integer transform() {\n" + "r1=removeBlankSpace(\"" + StringUtils.specCharToString(" a b\nc\rd e \u000Cf\r\n") + "\");\n" + "printErr(r1);\n" + "str_empty = removeBlankSpace('');\n" + "str_null = removeBlankSpace(null);\n" + "return 0;\n" + "}\n"; doCompile(expStr, "test_removeBlankSpace"); check("r1", "abcdef"); check("str_empty", ""); check("str_null", null); } public void test_stringlib_removeNonPrintable() { doCompile("test_stringlib_removeNonPrintable"); check("nonPrintableRemoved", "AHOJ"); check("test_empty", ""); check("test_null", null); } public void test_stringlib_getAlphanumericChars() { String expStr = "string an1;\n " + "string an2;\n" + "string an3;\n" + "string an4;\n" + "string an5;\n" + "string an6;\n" + "string an7;\n" + "string an8;\n" + "string an9;\n" + "string an10;\n" + "string an11;\n" + "string an12;\n" + "string an13;\n" + "string an14;\n" + "string an15;\n" + "function integer transform() {\n" + "an1=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\");\n" + "an2=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,true);\n" + "an3=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,false);\n" + "an4=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",false,true);\n" + "an5=getAlphanumericChars(\"\");\n" + "an6=getAlphanumericChars(\"\",true,true);\n"+ "an7=getAlphanumericChars(\"\",true,false);\n"+ "an8=getAlphanumericChars(\"\",false,true);\n"+ "an9=getAlphanumericChars(null);\n" + "an10=getAlphanumericChars(null,false,false);\n" + "an11=getAlphanumericChars(null,true,false);\n" + "an12=getAlphanumericChars(null,false,true);\n" + "an13=getAlphanumericChars(' 0 ľeškó11');\n" + "an14=getAlphanumericChars(' 0 ľeškó11', false, false);\n" + //CLO-1174 "an15=getAlphanumericChars('" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "',false,false);\n" + "return 0;\n" + "}\n"; doCompile(expStr, "test_getAlphanumericChars"); check("an1", "a1bcde2f"); check("an2", "a1bcde2f"); check("an3", "abcdef"); check("an4", "12"); check("an5", ""); check("an6", ""); check("an7", ""); check("an8", ""); check("an9", null); check("an10", null); check("an11", null); check("an12", null); check("an13", "0ľeškó11"); check("an14"," 0 ľeškó11"); //CLO-1174 String tmp = StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n"); check("an15", tmp); } public void test_stringlib_indexOf(){ doCompile("test_stringlib_indexOf"); check("index",2); check("index1",9); check("index2",0); check("index3",-1); check("index4",6); check("index5",-1); check("index6",0); check("index7",4); check("index8",4); check("index9", -1); check("index10", 2); check("index_empty1", -1); check("index_empty2", 0); check("index_empty3", 0); check("index_empty4", -1); } public void test_stringlib_indexOf_expect_error(){ //test: second arg is null - test1 try { doCompile("integer index;function integer transform() {index = indexOf('hello world',null); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: second arg is null - test2 try { doCompile("integer index;function integer transform() {index = indexOf('',null); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: first arg is null - test1 try { doCompile("integer index;function integer transform() {index = indexOf(null,'a'); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: first arg is null - test2 try { doCompile("integer index;function integer transform() {index = indexOf(null,''); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: both args are null try { doCompile("integer index;function integer transform() {index = indexOf(null,null); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_removeDiacritic(){ doCompile("test_stringlib_removeDiacritic"); check("test","tescik"); check("test1","zabicka"); check("test_empty", ""); check("test_null", null); } public void test_stringlib_translate(){ doCompile("test_stringlib_translate"); check("trans","hippi"); check("trans1","hipp"); check("trans2","hippi"); check("trans3",""); check("trans4","y lanuaX nXXd thX lXttXr X"); check("trans5", "hello"); check("test_empty1", ""); check("test_empty2", ""); check("test_null", null); } public void test_stringlib_translate_expect_error(){ try { doCompile("function integer transform(){string test = translate('bla bla',null,'o');return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate('bla bla','a',null);return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate('bla bla',null,null);return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate(null,'a',null);return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate(null,null,'a');return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate(null,null,null);return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_removeNonAscii(){ doCompile("test_stringlib_removeNonAscii"); check("test1", "Sun is shining"); check("test2", ""); check("test_empty", ""); check("test_null", null); } public void test_stringlib_chop() { doCompile("test_stringlib_chop"); check("s1", "hello"); check("s6", "hello"); check("s5", "hello"); check("s2", "hello"); check("s7", "helloworld"); check("s3", "hello "); check("s4", "hello"); check("s8", "hello"); check("s9", "world"); check("s10", "hello"); check("s11", "world"); check("s12", "mark.twain"); check("s13", "two words"); check("s14", ""); check("s15", ""); check("s16", ""); check("s17", ""); check("s18", ""); check("s19", "word"); check("s20", ""); check("s21", ""); check("s22", "mark.twain"); } public void test_stringlib_chop_expect_error() { //test: arg is null try { doCompile("string test;function integer transform() {test = chop(null);return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp pattern is null try { doCompile("string test;function integer transform() {test = chop('aaa', null);return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp pattern is null - test 2 try { doCompile("string test;function integer transform() {test = chop('', null);return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: arg is null try { doCompile("string test;function integer transform() {test = chop(null, 'aaa');return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: arg is null - test2 try { doCompile("string test;function integer transform() {test = chop(null, '');return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: arg is null - test3 try { doCompile("string test;function integer transform() {test = chop(null, null);return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } } //-------------------------- MathLib Tests ------------------------ public void test_bitwise_bitSet(){ doCompile("test_bitwise_bitSet"); check("test1", 3); check("test2", 15); check("test3", 34); check("test4", 3l); check("test5", 15l); check("test6", 34l); } public void test_bitwise_bitSet_expect_error(){ try { doCompile("function integer transform(){" + "integer var1 = null;" + "integer var2 = 3;" + "boolean var3 = false;" + "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer var1 = 512;" + "integer var2 = null;" + "boolean var3 = false;" + "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer var1 = 512;" + "integer var2 = 3;" + "boolean var3 = null;" + "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = 512l;" + "integer var2 = 3;" + "boolean var3 = null;" + "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = 512l;" + "integer var2 = null;" + "boolean var3 = true;" + "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = null;" + "integer var2 = 3;" + "boolean var3 = true;" + "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_bitIsSet(){ doCompile("test_bitwise_bitIsSet"); check("test1", true); check("test2", false); check("test3", false); check("test4", false); check("test5", true); check("test6", false); check("test7", false); check("test8", false); } public void test_bitwise_bitIsSet_expect_error(){ try { doCompile("function integer transform(){integer i = null; boolean b = bitIsSet(i,3); return 0;}","test_bitwise_bitIsSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = null; boolean b = bitIsSet(11,i); return 0;}","test_bitwise_bitIsSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = null; boolean b = bitIsSet(i,3); return 0;}","test_bitwise_bitIsSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = 12l; boolean b = bitIsSet(i,null); return 0;}","test_bitwise_bitIsSet_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_or() { doCompile("test_bitwise_or"); check("resultInt1", 1); check("resultInt2", 1); check("resultInt3", 3); check("resultInt4", 3); check("resultLong1", 1l); check("resultLong2", 1l); check("resultLong3", 3l); check("resultLong4", 3l); check("resultMix1", 15L); check("resultMix2", 15L); } public void test_bitwise_or_expect_error(){ try { doCompile("function integer transform(){" + "integer input1 = 12; " + "integer input2 = null; " + "integer i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer input1 = null; " + "integer input2 = 13; " + "integer i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long input1 = null; " + "long input2 = 13l; " + "long i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long input1 = 23l; " + "long input2 = null; " + "long i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_and() { doCompile("test_bitwise_and"); check("resultInt1", 0); check("resultInt2", 1); check("resultInt3", 0); check("resultInt4", 1); check("resultLong1", 0l); check("resultLong2", 1l); check("resultLong3", 0l); check("resultLong4", 1l); check("test_mixed1", 4l); check("test_mixed2", 4l); } public void test_bitwise_and_expect_error(){ try { doCompile("function integer transform(){\n" + "integer a = null; integer b = 16;\n" + "integer i = bitAnd(a,b);\n" + "return 0;}", "test_bitwise_end_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "integer a = 16; integer b = null;\n" + "integer i = bitAnd(a,b);\n" + "return 0;}", "test_bitwise_end_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "long a = 16l; long b = null;\n" + "long i = bitAnd(a,b);\n" + "return 0;}", "test_bitwise_end_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "long a = null; long b = 10l;\n" + "long i = bitAnd(a,b);\n" + "return 0;}", "test_bitwise_end_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_xor() { doCompile("test_bitwise_xor"); check("resultInt1", 1); check("resultInt2", 0); check("resultInt3", 3); check("resultInt4", 2); check("resultLong1", 1l); check("resultLong2", 0l); check("resultLong3", 3l); check("resultLong4", 2l); check("test_mixed1", 15L); check("test_mixed2", 60L); } public void test_bitwise_xor_expect_error(){ try { doCompile("function integer transform(){" + "integer var1 = null;" + "integer var2 = 123;" + "integer i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer var1 = 23;" + "integer var2 = null;" + "integer i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = null;" + "long var2 = 123l;" + "long i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = 2135l;" + "long var2 = null;" + "long i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_lshift() { doCompile("test_bitwise_lshift"); check("resultInt1", 2); check("resultInt2", 4); check("resultInt3", 10); check("resultInt4", 20); check("resultInt5", -2147483648); check("resultLong1", 2l); check("resultLong2", 4l); check("resultLong3", 10l); check("resultLong4", 20l); check("resultLong5",-9223372036854775808l); check("test_mixed1", 176l); check("test_mixed2", 616l); } public void test_bitwise_lshift_expect_error(){ try { doCompile("function integer transform(){integer input = null; integer i = bitLShift(input,2); return 0;}","test_bitwise_lshift_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer input = null; integer i = bitLShift(44,input); return 0;}","test_bitwise_lshift_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; long i = bitLShift(input,4l); return 0;}","test_bitwise_lshift_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; long i = bitLShift(444l,input); return 0;}","test_bitwise_lshift_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_rshift() { doCompile("test_bitwise_rshift"); check("resultInt1", 2); check("resultInt2", 0); check("resultInt3", 4); check("resultInt4", 2); check("resultLong1", 2l); check("resultLong2", 0l); check("resultLong3", 4l); check("resultLong4", 2l); check("test_neg1", 0); check("test_neg2", 0); check("test_neg3", 0l); check("test_neg4", 0l); // CLO-1399 check("test_mix1", 30l); check("test_mix2", 39l); } public void test_bitwise_rshift_expect_error(){ try { doCompile("function integer transform(){" + "integer var1 = 23;" + "integer var2 = null;" + "integer i = bitRShift(var1,var2);" + "return 0;}","test_bitwise_rshift_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){" + "integer var1 = null;" + "integer var2 = 78;" + "integer u = bitRShift(var1,var2);" + "return 0;}","test_bitwise_rshift_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){" + "long var1 = 23l;" + "long var2 = null;" + "long l =bitRShift(var1,var2);" + "return 0;}","test_bitwise_rshift_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){" + "long var1 = null;" + "long var2 = 84l;" + "long l = bitRShift(var1,var2);" + "return 0;}","test_bitwise_rshift_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_bitwise_negate() { doCompile("test_bitwise_negate"); check("resultInt", -59081717); check("resultLong", -3321654987654105969L); check("test_zero_int", -1); check("test_zero_long", -1l); } public void test_bitwise_negate_expect_error(){ try { doCompile("function integer transform(){integer input = null; integer i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; long i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_set_bit() { doCompile("test_set_bit"); check("resultInt1", 0x2FF); check("resultInt2", 0xFB); check("resultLong1", 0x4000000000000l); check("resultLong2", 0xFFDFFFFFFFFFFFFl); check("resultBool1", true); check("resultBool2", false); check("resultBool3", true); check("resultBool4", false); } public void test_mathlib_abs() { doCompile("test_mathlib_abs"); check("absIntegerPlus", new Integer(10)); check("absIntegerMinus", new Integer(1)); check("absLongPlus", new Long(10)); check("absLongMinus", new Long(1)); check("absDoublePlus", new Double(10.0)); check("absDoubleMinus", new Double(1.0)); check("absDecimalPlus", new BigDecimal(5.0)); check("absDecimalMinus", new BigDecimal(5.0)); } public void test_mathlib_abs_expect_error(){ try { doCompile("function integer transform(){ \n " + "integer tmp;\n " + "tmp = null; \n" + " integer i = abs(tmp); \n " + "return 0;}", "test_mathlib_abs_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){ \n " + "long tmp;\n " + "tmp = null; \n" + "long i = abs(tmp); \n " + "return 0;}", "test_mathlib_abs_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){ \n " + "double tmp;\n " + "tmp = null; \n" + "double i = abs(tmp); \n " + "return 0;}", "test_mathlib_abs_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){ \n " + "decimal tmp;\n " + "tmp = null; \n" + "decimal i = abs(tmp); \n " + "return 0;}", "test_mathlib_abs_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_ceil() { doCompile("test_mathlib_ceil"); check("ceil1", -3.0); check("intResult", Arrays.asList(2.0, 3.0)); check("longResult", Arrays.asList(2.0, 3.0)); check("doubleResult", Arrays.asList(3.0, -3.0)); check("decimalResult", Arrays.asList(new BigDecimal(3.0), new BigDecimal(-3.0))); } public void test_mathlib_ceil_expect_error(){ try { doCompile("function integer transform(){integer var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal var = null; decimal d = ceil(var); return 0;}","test_mathlib_ceil_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_e() { doCompile("test_mathlib_e"); check("varE", Math.E); } public void test_mathlib_exp() { doCompile("test_mathlib_exp"); check("ex", Math.exp(1.123)); check("test1", Math.exp(2)); check("test2", Math.exp(22)); check("test3", Math.exp(23)); check("test4", Math.exp(94)); } public void test_mathlib_exp_expect_error(){ try { doCompile("function integer transform(){integer input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_floor() { doCompile("test_mathlib_floor"); check("floor1", -4.0); check("intResult", Arrays.asList(2.0, 3.0)); check("longResult", Arrays.asList(2.0, 3.0)); check("doubleResult", Arrays.asList(2.0, -4.0)); check("decimalResult", Arrays.asList(new BigDecimal("2"), new BigDecimal("-4"))); } public void test_math_lib_floor_expect_error(){ try { doCompile("function integer transform(){integer input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input= null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; decimal d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_log() { doCompile("test_mathlib_log"); check("ln", Math.log(3)); check("test_int", Math.log(32)); check("test_long", Math.log(14l)); check("test_double", Math.log(12.9)); check("test_decimal", Math.log(23.7)); } public void test_math_log_expect_error(){ try { doCompile("function integer transform(){integer input = null; number n = log(input); return 0;}","test_math_log_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){long input = null; number n = log(input); return 0;}","test_math_log_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){decimal input = null; number n = log(input); return 0;}","test_math_log_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){double input = null; number n = log(input); return 0;}","test_math_log_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_mathlib_log10() { doCompile("test_mathlib_log10"); check("varLog10", Math.log10(3)); check("test_int", Math.log10(5)); check("test_long", Math.log10(90L)); check("test_decimal", Math.log10(32.1)); check("test_number", Math.log10(84.12)); } public void test_mathlib_log10_expect_error(){ try { doCompile("function integer transform(){integer input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_pi() { doCompile("test_mathlib_pi"); check("varPi", Math.PI); } public void test_mathlib_pow() { doCompile("test_mathlib_pow"); check("power1", Math.pow(3,1.2)); check("power2", Double.NaN); check("intResult", Arrays.asList(new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"))); check("longResult", Arrays.asList(new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"))); check("doubleResult", Arrays.asList(new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"))); check("decimalResult", Arrays.asList(new BigDecimal("8.000"), new BigDecimal("8.000"), new BigDecimal("8.000"), new BigDecimal("8.000"))); } public void test_mathlib_pow_expect_error(){ try { doCompile("function integer transform(){integer var1 = 12; integer var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer var1 = null; integer var2 = 2; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long var1 = 12l; long var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long var1 = null; long var2 = 12L; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number var1 = 12.2; number var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number var1 = null; number var2 = 2.1; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal var1 = 12.2d; decimal var2 = null; decimal n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal var1 = null; decimal var2 = 45.3d; decimal n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } } /* * The equals() method also takes the scale into account, * CTL uses compareTo() instead. */ private void compareDecimals(List<BigDecimal> expected, List<BigDecimal> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < actual.size(); i++) { assertTrue("Expected: " + expected.get(i) + ", actual: " + actual.get(i), expected.get(i).compareTo(actual.get(i)) == 0); } } @SuppressWarnings("unchecked") public void test_mathlib_round() { doCompile("test_mathlib_round"); check("round1", -4l); check("intResult", Arrays.asList(2l, 3l)); check("longResult", Arrays.asList(2l, 3l)); check("doubleResult", Arrays.asList(2l, 4l)); //CLO-1835 // check("decimalResult", Arrays.asList(new BigDecimal("2"), new BigDecimal("4"))); // negative precision means the number of places after the decimal point // positive precision before the decimal point List<BigDecimal> expected = Arrays.asList( new BigDecimal("0"), new BigDecimal("1000000"), new BigDecimal("1200000"), new BigDecimal("1230000"), new BigDecimal("1235000"), // rounded up new BigDecimal("1234600"), // rounded up new BigDecimal("1234570"), // rounded up new BigDecimal("1234567"), new BigDecimal("1234567.1"), new BigDecimal("1234567.12"), new BigDecimal("1234567.123"), new BigDecimal("1234567.1235"), // rounded up new BigDecimal("1234567.12346"), // rounded up new BigDecimal("1234567.123457"), // rounded up new BigDecimal("1234567.1234567") ); //CLO-1835 compareDecimals(expected, (List<BigDecimal>) getVariable("decimal2Result")); //CLO-1832 check("intWithPrecisionResult", 1234d); check("longWithPrecisionResult", 123456d); check("ret1", 1234d); check("ret2", 13565d); } public void test_mathlib_round_expect_error(){ try { doCompile("function integer transform(){number input = null; long l = round(input);return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; decimal l = round(input);return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_sqrt() { doCompile("test_mathlib_sqrt"); check("sqrtPi", Math.sqrt(Math.PI)); check("sqrt9", Math.sqrt(9)); check("test_int", 2.0); check("test_long", Math.sqrt(64L)); check("test_num", Math.sqrt(86.9)); check("test_dec", Math.sqrt(34.5)); } public void test_mathlib_sqrt_expect_error(){ try { doCompile("function integer transform(){integer input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_randomInteger(){ doCompile("test_mathlib_randomInteger"); assertNotNull(getVariable("test1")); check("test2", 2); } public void test_mathlib_randomInteger_expect_error(){ try { doCompile("function integer transform(){integer i = randomInteger(1,null); return 0;}","test_mathlib_randomInteger_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = randomInteger(null,null); return 0;}","test_mathlib_randomInteger_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = randomInteger(null, -3); return 0;}","test_mathlib_randomInteger_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = randomInteger(1,-7); return 0;}","test_mathlib_randomInteger_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_randomLong(){ doCompile("test_mathlib_randomLong"); assertNotNull(getVariable("test1")); check("test2", 15L); } public void test_mathlib_randomLong_expect_error(){ try { doCompile("function integer transform(){long lo = randomLong(15L, null); return 0;}","test_mathlib_randomLong_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long lo = randomLong(null, null); return 0;}","test_mathlib_randomLong_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long lo = randomLong(null, 15L); return 0;}","test_mathlib_randomLong_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long lo = randomLong(15L, 10L); return 0;}","test_mathlib_randomLong_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_setRandomSeed_expect_error(){ try { doCompile("function integer transform(){long l = null; setRandomSeed(l); return 0;}","test_mathlib_setRandomSeed_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = null; setRandomSeed(i); return 0;}","test_mathlib_setRandomSeed_expect_error"); fail(); } catch (Exception e) { // do nothing } } //-------------------------DateLib tests---------------------- public void test_datelib_cache() { doCompile("test_datelib_cache"); check("b11", true); check("b12", true); check("b21", true); check("b22", true); check("b31", true); check("b32", true); check("b41", true); check("b42", true); checkEquals("date3", "date3d"); checkEquals("date4", "date4d"); checkEquals("date7", "date7d"); checkEquals("date8", "date8d"); } public void test_datelib_trunc() { doCompile("test_datelib_trunc"); check("truncDate", new GregorianCalendar(2004, 00, 02).getTime()); } public void test_datelib_trunc_except_error(){ try { doCompile("function integer transform(){trunc(null); return 0;}","test_datelib_trunc_except_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = null; trunc(d); return 0;}","test_datelib_trunc_except_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_truncDate() { doCompile("test_datelib_truncDate"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)}; cal.clear(); cal.set(Calendar.HOUR_OF_DAY, portion[0]); cal.set(Calendar.MINUTE, portion[1]); cal.set(Calendar.SECOND, portion[2]); cal.set(Calendar.MILLISECOND, portion[3]); check("truncBornDate", cal.getTime()); } public void test_datelib_truncDate_except_error(){ try { doCompile("function integer transform(){truncDate(null); return 0;}","test_datelib_truncDate_except_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = null; truncDate(d); return 0;}","test_datelib_truncDate_except_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_today() { doCompile("test_datelib_today"); Date expectedDate = new Date(); //the returned date does not need to be exactly the same date which is in expectedData variable //let say 1000ms is tolerance for equality assertTrue("todayDate", Math.abs(expectedDate.getTime() - ((Date) getVariable("todayDate")).getTime()) < 1000); } public void test_datelib_zeroDate() { doCompile("test_datelib_zeroDate"); check("zeroDate", new Date(0)); } public void test_datelib_dateDiff() { doCompile("test_datelib_dateDiff"); long diffYears = Years.yearsBetween(new DateTime(), new DateTime(BORN_VALUE)).getYears(); check("ddiff", diffYears); long[] results = {1, 12, 52, 365, 8760, 525600, 31536000, 31536000000L}; String[] vars = {"ddiffYears", "ddiffMonths", "ddiffWeeks", "ddiffDays", "ddiffHours", "ddiffMinutes", "ddiffSeconds", "ddiffMilliseconds"}; for (int i = 0; i < results.length; i++) { check(vars[i], results[i]); } } public void test_datelib_dateDiff_epect_error(){ try { doCompile("function integer transform(){long i = dateDiff(null,today(),millisec);return 0;}","test_datelib_dateDiff_epect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = dateDiff(today(),null,millisec);return 0;}","test_datelib_dateDiff_epect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = dateDiff(today(),today(),null);return 0;}","test_datelib_dateDiff_epect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_dateAdd() { doCompile("test_datelib_dateAdd"); check("datum", new Date(BORN_MILLISEC_VALUE + 100)); } public void test_datelib_dateAdd_expect_error(){ try { doCompile("function integer transform(){date d = dateAdd(null,120,second); return 0;}","test_datelib_dateAdd_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = dateAdd(today(),null,second); return 0;}","test_datelib_dateAdd_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = dateAdd(today(),120,null); return 0;}","test_datelib_dateAdd_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_extractTime() { doCompile("test_datelib_extractTime"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)}; cal.clear(); cal.set(Calendar.HOUR_OF_DAY, portion[0]); cal.set(Calendar.MINUTE, portion[1]); cal.set(Calendar.SECOND, portion[2]); cal.set(Calendar.MILLISECOND, portion[3]); check("bornExtractTime", cal.getTime()); check("originalDate", BORN_VALUE); check("nullDate", null); check("nullDate2", null); } public void test_datelib_extractDate() { doCompile("test_datelib_extractDate"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); int[] portion = new int[]{cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH), cal.get(Calendar.YEAR)}; cal.clear(); cal.set(Calendar.DAY_OF_MONTH, portion[0]); cal.set(Calendar.MONTH, portion[1]); cal.set(Calendar.YEAR, portion[2]); check("bornExtractDate", cal.getTime()); check("originalDate", BORN_VALUE); check("nullDate", null); check("nullDate2", null); } public void test_datelib_createDate() { doCompile("test_datelib_createDate"); Calendar cal = Calendar.getInstance(); // no time zone cal.clear(); cal.set(2013, 5, 11); check("date1", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); check("dateTime1", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); cal.set(Calendar.MILLISECOND, 123); check("dateTimeMillis1", cal.getTime()); // literal cal.setTimeZone(TimeZone.getTimeZone("GMT+5")); cal.clear(); cal.set(2013, 5, 11); check("date2", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); check("dateTime2", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); cal.set(Calendar.MILLISECOND, 123); check("dateTimeMillis2", cal.getTime()); // variable cal.clear(); cal.set(2013, 5, 11); check("date3", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); check("dateTime3", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); cal.set(Calendar.MILLISECOND, 123); check("dateTimeMillis3", cal.getTime()); Calendar cal1 = Calendar.getInstance(); cal1.set(2011, 10, 20, 0, 0, 0); cal1.set(Calendar.MILLISECOND, 0); Date d = cal1.getTime(); // CLO-1674 check("ret1", d); check("ret2", d); cal1.clear(); cal1.set(2011, 10, 20, 4, 20, 11); cal1.set(Calendar.MILLISECOND, 0); check("ret3", cal1.getTime()); cal1.clear(); cal1.set(2011, 10, 20, 4, 20, 11); cal1.set(Calendar.MILLISECOND, 123); d = cal1.getTime(); check("ret4", d); // CLO-1674 check("ret5", d); } public void test_datelib_createDate_expect_error(){ try { doCompile("function integer transform(){date d = createDate(null, null, null); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, null, null); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, 10, null); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, 11, 20, null, 5, 45); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, 11, 20, 12, null, 45); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, 11, 20, 12, 5, null); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer str = null; date d = createDate(1970, 11, 20, 12, 5, 45, str); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_getPart() { doCompile("test_datelib_getPart"); Calendar cal = Calendar.getInstance(); cal.clear(); cal.setTimeZone(TimeZone.getTimeZone("GMT+1")); cal.set(2013, 5, 11, 14, 46, 34); cal.set(Calendar.MILLISECOND, 123); Date date = cal.getTime(); cal = Calendar.getInstance(); cal.setTime(date); // no time zone check("year1", cal.get(Calendar.YEAR)); check("month1", cal.get(Calendar.MONTH) + 1); check("day1", cal.get(Calendar.DAY_OF_MONTH)); check("hour1", cal.get(Calendar.HOUR_OF_DAY)); check("minute1", cal.get(Calendar.MINUTE)); check("second1", cal.get(Calendar.SECOND)); check("millisecond1", cal.get(Calendar.MILLISECOND)); cal.setTimeZone(TimeZone.getTimeZone("GMT+5")); // literal check("year2", cal.get(Calendar.YEAR)); check("month2", cal.get(Calendar.MONTH) + 1); check("day2", cal.get(Calendar.DAY_OF_MONTH)); check("hour2", cal.get(Calendar.HOUR_OF_DAY)); check("minute2", cal.get(Calendar.MINUTE)); check("second2", cal.get(Calendar.SECOND)); check("millisecond2", cal.get(Calendar.MILLISECOND)); // variable check("year3", cal.get(Calendar.YEAR)); check("month3", cal.get(Calendar.MONTH) + 1); check("day3", cal.get(Calendar.DAY_OF_MONTH)); check("hour3", cal.get(Calendar.HOUR_OF_DAY)); check("minute3", cal.get(Calendar.MINUTE)); check("second3", cal.get(Calendar.SECOND)); check("millisecond3", cal.get(Calendar.MILLISECOND)); check("year_null", 2013); check("month_null", 6); check("day_null", 11); check("hour_null", 15); check("minute_null", cal.get(Calendar.MINUTE)); check("second_null", cal.get(Calendar.SECOND)); check("milli_null", cal.get(Calendar.MILLISECOND)); check("year_null2", null); check("month_null2", null); check("day_null2", null); check("hour_null2", null); check("minute_null2", null); check("second_null2", null); check("milli_null2", null); check("year_null3", null); check("month_null3", null); check("day_null3", null); check("hour_null3", null); check("minute_null3", null); check("second_null3", null); check("milli_null3", null); } public void test_datelib_randomDate() { doCompile("test_datelib_randomDate"); final long HOUR = 60L * 60L * 1000L; Date BORN_VALUE_NO_MILLIS = new Date(BORN_VALUE.getTime() / 1000L * 1000L); check("noTimeZone1", BORN_VALUE); check("noTimeZone2", BORN_VALUE_NO_MILLIS); check("withTimeZone1", new Date(BORN_VALUE_NO_MILLIS.getTime() + 2*HOUR)); // timezone changes from GMT+5 to GMT+3 check("withTimeZone2", new Date(BORN_VALUE_NO_MILLIS.getTime() - 2*HOUR)); // timezone changes from GMT+3 to GMT+5 assertNotNull(getVariable("patt_null")); assertNotNull(getVariable("ret1")); assertNotNull(getVariable("ret2")); } public void test_datelib_randomDate_expect_error(){ try { doCompile("function integer transform(){date a = null; date b = today(); " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date a = today(); date b = null; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date a = null; date b = null; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long a = 843484317231l; long b = null; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long a = null; long b = 12115641158l; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long a = null; long b = null; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "string a = null; string b = '2006-11-12'; string pattern='yyyy-MM-dd';" + "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "string a = '2006-11-12'; string b = null; string pattern='yyyy-MM-dd';" + "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } //wrong format try { doCompile("function integer transform(){" + "string a = '2006-10-12'; string b = '2006-11-12'; string pattern='yyyy:MM:dd';" + "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } //start date bigger then end date try { doCompile("function integer transform(){" + "string a = '2008-10-12'; string b = '2006-11-12'; string pattern='yyyy-MM-dd';" + "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } } //-----------------Convert Lib tests----------------------- public void test_convertlib_json2xml(){ doCompile("test_convertlib_json2xml"); String xmlChunk ="" + "<lastName>Smith</lastName>" + "<phoneNumber>" + "<number>212 555-1234</number>" + "<type>home</type>" + "</phoneNumber>" + "<phoneNumber>" + "<number>646 555-4567</number>" + "<type>fax</type>" + "</phoneNumber>" + "<address>" + "<streetAddress>21 2nd Street</streetAddress>" + "<postalCode>10021</postalCode>" + "<state>NY</state>" + "<city>New York</city>" + "</address>" + "<age>25</age>" + "<firstName>John</firstName>"; check("ret", xmlChunk); check("ret2", "<name/>"); check("ret3", "<address></address>"); check("ret4", "</>"); check("ret5", "<#/>"); check("ret6", "</>/<//>"); check("ret7",""); check("ret8", "<>Urgot</>"); } public void test_convertlib_json2xml_expect_error(){ try { doCompile("function integer transform(){string str = json2xml(''); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string str = json2xml(null); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string str = json2xml('{\"name\"}'); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string str = json2xml('{\"name\":}'); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string str = json2xml('{:\"name\"}'); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_convertlib_xml2json(){ doCompile("test_convertlib_xml2json"); String json = "{\"lastName\":\"Smith\",\"phoneNumber\":[{\"number\":\"212 555-1234\",\"type\":\"home\"},{\"number\":\"646 555-4567\",\"type\":\"fax\"}],\"address\":{\"streetAddress\":\"21 2nd Street\",\"postalCode\":10021,\"state\":\"NY\",\"city\":\"New York\"},\"age\":25,\"firstName\":\"John\"}"; check("ret1", json); check("ret2", "{\"name\":\"Renektor\"}"); check("ret3", "{}"); check("ret4", "{\"address\":\"\"}"); check("ret5", "{\"age\":32}"); check("ret6", "{\"b\":\"\"}"); check("ret7", "{\"char\":{\"name\":\"Anivia\",\"lane\":\"mid\"}}"); check("ret8", "{\"#\":\"/\"}"); } public void test_convertlib_xml2json_expect_error(){ try { doCompile("function integer transform(){string json = xml2json(null); return 0;}","test_convertlib_xml2json_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string json = xml2json('<></>'); return 0;}","test_convertlib_xml2json_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string json = xml2json('<#>/</>'); return 0;}","test_convertlib_xml2json_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_cache() { // set default locale to en.US so the date is formatted uniformly on all systems Locale.setDefault(Locale.US); doCompile("test_convertlib_cache"); Calendar cal = Calendar.getInstance(); cal.set(2000, 6, 20, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Date checkDate = cal.getTime(); final SimpleDateFormat format = new SimpleDateFormat(); format.applyPattern("yyyy MMM dd"); check("sdate1", format.format(new Date())); check("sdate2", format.format(new Date())); check("date01", checkDate); check("date02", checkDate); check("date03", checkDate); check("date04", checkDate); check("date11", checkDate); check("date12", checkDate); check("date13", checkDate); } public void test_convertlib_base64byte() { doCompile("test_convertlib_base64byte"); assertTrue(Arrays.equals((byte[])getVariable("base64input"), Base64.decode("The quick brown fox jumps over the lazy dog"))); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_bits2str() { doCompile("test_convertlib_bits2str"); check("bitsAsString1", "00000000"); check("bitsAsString2", "11111111"); check("bitsAsString3", "010100000100110110100000"); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_bool2num() { doCompile("test_convertlib_bool2num"); check("resultTrue", 1); check("resultFalse", 0); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_byte2base64() throws UnsupportedEncodingException { doCompile("test_convertlib_byte2base64"); check("inputBase64", Base64.encodeBytes("Abeceda zedla deda".getBytes())); String longText = (String) getVariable("longText"); byte[] longTextBytes = longText.getBytes("UTF-8"); String inputBase64wrapped = Base64.encodeBytes(longTextBytes, Base64.NO_OPTIONS); String inputBase64nowrap = Base64.encodeBytes(longTextBytes, Base64.DONT_BREAK_LINES); check("inputBase64wrapped", inputBase64wrapped); assertTrue(((String) getVariable("inputBase64wrapped")).indexOf('\n') >= 0); check("inputBase64nowrap", inputBase64nowrap); assertTrue(((String) getVariable("inputBase64nowrap")).indexOf('\n') < 0); check("nullLiteralOutput", null); check("nullVariableOutput", null); check("nullLiteralOutputWrapped", null); check("nullVariableOutputWrapped", null); check("nullLiteralOutputNowrap", null); check("nullVariableOutputNowrap", null); } public void test_convertlib_byte2base64_expect_error(){ try { doCompile("function integer transform(){boolean b = null; string s = byte2base64(str2byte('Rengar', 'utf-8'), b);return 0;}","test_convertlib_byte2base64_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = byte2base64(str2byte('Rengar', 'utf-8'), null);return 0;}","test_convertlib_byte2base64_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_byte2hex() { doCompile("test_convertlib_byte2hex"); check("hexResult", "41626563656461207a65646c612064656461"); check("test_null1", null); check("test_null2", null); } public void test_convertlib_date2long() { doCompile("test_convertlib_date2long"); check("bornDate", BORN_MILLISEC_VALUE); check("zeroDate", 0l); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_date2num() { doCompile("test_convertlib_date2num"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); check("yearDate", 1987); check("monthDate", 5); check("secondDate", 0); check("yearBorn", cal.get(Calendar.YEAR)); check("monthBorn", cal.get(Calendar.MONTH) + 1); //Calendar enumerates months from 0, not 1; check("secondBorn", cal.get(Calendar.SECOND)); check("yearMin", 1970); check("monthMin", 1); check("weekMin", 1); check("weekMinCs", 1); check("dayMin", 1); check("hourMin", 1); //TODO: check! check("minuteMin", 0); check("secondMin", 0); check("millisecMin", 0); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_date2num_expect_error(){ try { doCompile("function integer transform(){number num = date2num(1982-09-02,null); return 0;}","test_convertlib_date2num_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){number num = date2num(1982-09-02,null,null); return 0;}","test_convertlib_date2num_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string s = null; number num = date2num(1982-09-02,null,s); return 0;}","test_convertlib_date2num_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string s = null; number num = date2num(1982-09-02,year,s); return 0;}","test_convertlib_date2num_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_convertlib_date2str() { doCompile("test_convertlib_date2str"); check("inputDate", "1987:05:12"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd"); check("bornDate", sdf.format(BORN_VALUE)); SimpleDateFormat sdfCZ = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("cs.CZ")); check("czechBornDate", sdfCZ.format(BORN_VALUE)); SimpleDateFormat sdfEN = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("en")); check("englishBornDate", sdfEN.format(BORN_VALUE)); { String[] locales = {"en", "pl", null, "cs.CZ", null}; List<String> expectedDates = new ArrayList<String>(); for (String locale: locales) { expectedDates.add(new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale(locale)).format(BORN_VALUE)); } check("loopTest", expectedDates); } SimpleDateFormat sdfGMT8 = new SimpleDateFormat("yyyy:MMMM:dd z", MiscUtils.createLocale("en")); sdfGMT8.setTimeZone(TimeZone.getTimeZone("GMT+8")); check("timeZone", sdfGMT8.format(BORN_VALUE)); check("nullRet", null); check("nullRet2", null); check("nullRet3", "2011-04-15"); check("nullRet4", "2011-04-15"); check("nullRet5", "2011-04-15"); } public void test_convertlib_date2str_expect_error(){ try { doCompile("function integer transform(){string str = date2str(2001-12-15, 'xxx.MM.dd'); printErr(str); return 0;}","test_convertlib_date2str_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_decimal2double() { doCompile("test_convertlib_decimal2double"); check("toDouble", 0.007d); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_decimal2double_expect_error(){ try { String str ="function integer transform(){" + "decimal dec = str2decimal('9"+ Double.MAX_VALUE +"');" + "double dou = decimal2double(dec);" + "return 0;}" ; doCompile(str,"test_convertlib_decimal2double_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_decimal2integer() { doCompile("test_convertlib_decimal2integer"); check("toInteger", 0); check("toInteger2", -500); check("toInteger3", 1000000); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_decimal2integer_expect_error(){ try { doCompile("function integer transform(){integer int = decimal2integer(352147483647.23);return 0;}","test_convertlib_decimal2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_decimal2long() { doCompile("test_convertlib_decimal2long"); check("toLong", 0l); check("toLong2", -500l); check("toLong3", 10000000000l); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_decimal2long_expect_error(){ try { doCompile("function integer transform(){long l = decimal2long(9759223372036854775807.25); return 0;}","test_convertlib_decimal2long_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_double2integer() { doCompile("test_convertlib_double2integer"); check("toInteger", 0); check("toInteger2", -500); check("toInteger3", 1000000); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_double2integer_expect_error(){ try { doCompile("function integer transform(){integer int = double2integer(352147483647.1); return 0;}","test_convertlib_double2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_double2long() { doCompile("test_convertlib_double2long"); check("toLong", 0l); check("toLong2", -500l); check("toLong3", 10000000000l); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_double2long_expect_error(){ try { doCompile("function integer transform(){long l = double2long(1.3759739E23); return 0;}","test_convertlib_double2long_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_getFieldName() { doCompile("test_convertlib_getFieldName"); check("fieldNames",Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency")); } public void test_convertlib_getFieldType() { doCompile("test_convertlib_getFieldType"); check("fieldTypes",Arrays.asList(DataFieldType.STRING.getName(), DataFieldType.NUMBER.getName(), DataFieldType.STRING.getName(), DataFieldType.DATE.getName(), DataFieldType.LONG.getName(), DataFieldType.INTEGER.getName(), DataFieldType.BOOLEAN.getName(), DataFieldType.BYTE.getName(), DataFieldType.DECIMAL.getName())); } public void test_convertlib_hex2byte() { doCompile("test_convertlib_hex2byte"); assertTrue(Arrays.equals((byte[])getVariable("fromHex"), BYTEARRAY_VALUE)); check("test_null", null); } public void test_convertlib_long2date() { doCompile("test_convertlib_long2date"); check("fromLong1", new Date(0)); check("fromLong2", new Date(50000000000L)); check("fromLong3", new Date(-5000L)); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_long2integer() { doCompile("test_convertlib_long2integer"); check("fromLong1", 10); check("fromLong2", -10); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_long2integer_expect_error(){ //this test should be expected to success in future try { doCompile("function integer transform(){integer i = long2integer(200032132463123L); return 0;}","test_convertlib_long2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_long2packDecimal() { doCompile("test_convertlib_long2packDecimal"); assertTrue(Arrays.equals((byte[])getVariable("packedLong"), new byte[] {5, 0, 12})); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_md5() { doCompile("test_convertlib_md5"); assertTrue(Arrays.equals((byte[])getVariable("md5Hash1"), Digest.digest(DigestType.MD5, "The quick brown fox jumps over the lazy dog"))); assertTrue(Arrays.equals((byte[])getVariable("md5Hash2"), Digest.digest(DigestType.MD5, BYTEARRAY_VALUE))); assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.MD5, ""))); } public void test_convertlib_md5_expect_error(){ //CLO-1254 try { doCompile("function integer transform(){string s = null; byte b = md5(s); return 0;}","test_convertlib_md5_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte s = null; byte b = md5(s); return 0;}","test_convertlib_md5_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_num2bool() { doCompile("test_convertlib_num2bool"); check("integerTrue", true); check("integerFalse", false); check("longTrue", true); check("longFalse", false); check("doubleTrue", true); check("doubleFalse", false); check("decimalTrue", true); check("decimalFalse", false); check("nullInt", null); check("nullLong", null); check("nullDouble", null); check("nullDecimal", null); } public void test_convertlib_num2str() { System.out.println("num2str() test:"); doCompile("test_convertlib_num2str"); check("intOutput", Arrays.asList("16", "10000", "20", "10", "1.235E3", "12 350 001 Kcs")); check("longOutput", Arrays.asList("16", "10000", "20", "10", "1.235E13", "12 350 001 Kcs")); check("doubleOutput", Arrays.asList("16.16", "0x1.028f5c28f5c29p4", "1.23548E3", "12 350 001,1 Kcs")); check("decimalOutput", Arrays.asList("16.16", "1235.44", "12 350 001,1 Kcs")); check("nullIntRet", Arrays.asList(null,null,null,null,"12","12",null,null)); check("nullLongRet", Arrays.asList(null,null,null,null,"12","12",null,null)); check("nullDoubleRet", Arrays.asList(null,null,null,null,"12.2","12.2",null,null)); check("nullDecRet", Arrays.asList(null,null,null,"12.2","12.2",null,null)); } public void test_convertlib_num2str_expect_error(){ try { doCompile("function integer transform(){integer var = null; string ret = num2str(12, var); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer var = null; string ret = num2str(12L, var); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer var = null; string ret = num2str(12.3, var); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string ret = num2str(12.3, 2); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string ret = num2str(12.3, 8); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_packdecimal2long() { doCompile("test_convertlib_packDecimal2long"); check("unpackedLong", PackedDecimal.parse(BYTEARRAY_VALUE)); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_sha() { doCompile("test_convertlib_sha"); assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA, "The quick brown fox jumps over the lazy dog"))); assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA, BYTEARRAY_VALUE))); assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.SHA, ""))); } public void test_convertlib_sha_expect_error(){ // CLO-1258 try { doCompile("function integer transform(){string s = null; byte b = sha(s); return 0;}","test_convertlib_sha_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte s = null; byte b = sha(s); return 0;}","test_convertlib_sha_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_sha256() { doCompile("test_convertlib_sha256"); assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA256, "The quick brown fox jumps over the lazy dog"))); assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA256, BYTEARRAY_VALUE))); assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.SHA256, ""))); } public void test_convertlib_sha256_expect_error(){ // CLO-1258 try { doCompile("function integer transform(){string a = null; byte b = sha256(a); return 0;}","test_convertlib_sha256_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte a = null; byte b = sha256(a); return 0;}","test_convertlib_sha256_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2bits() { doCompile("test_convertlib_str2bits"); //TODO: uncomment -> test will pass, but is that correct? assertTrue(Arrays.equals((byte[]) getVariable("textAsBits1"), new byte[] {0/*, 0, 0, 0, 0, 0, 0, 0*/})); assertTrue(Arrays.equals((byte[]) getVariable("textAsBits2"), new byte[] {-1/*, 0, 0, 0, 0, 0, 0, 0*/})); assertTrue(Arrays.equals((byte[]) getVariable("textAsBits3"), new byte[] {10, -78, 5/*, 0, 0, 0, 0, 0*/})); assertTrue(Arrays.equals((byte[]) getVariable("test_empty"), new byte[] {})); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_str2bool() { doCompile("test_convertlib_str2bool"); check("fromTrueString", true); check("fromFalseString", false); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_str2bool_expect_error(){ try { doCompile("function integer transform(){boolean b = str2bool('asd'); return 0;}","test_convertlib_str2bool_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){boolean b = str2bool(''); return 0;}","test_convertlib_str2bool_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_convertlib_str2date() { doCompile("test_convertlib_str2date"); Calendar cal = Calendar.getInstance(); cal.set(2005,10,19,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("date1", cal.getTime()); cal.clear(); cal.set(2050, 4, 19, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Date checkDate = cal.getTime(); check("date2", checkDate); check("date3", checkDate); cal.clear(); cal.setTimeZone(TimeZone.getTimeZone("GMT+8")); cal.set(2013, 04, 30, 17, 15, 12); check("withTimeZone1", cal.getTime()); cal.clear(); cal.setTimeZone(TimeZone.getTimeZone("GMT-8")); cal.set(2013, 04, 30, 17, 15, 12); check("withTimeZone2", cal.getTime()); assertFalse(getVariable("withTimeZone1").equals(getVariable("withTimeZone2"))); check("nullRet1", null); check("nullRet2", null); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); } public void test_convertlib_str2date_expect_error(){ try { doCompile("function integer transform(){date d = str2date('1987-11-17', 'dd.MM.yyyy'); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('1987-33-17', 'yyyy-MM-dd'); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('17.11.1987', null, 'cs.CZ'); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('17.11.1987', 'yyyy-MM-dd', null); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('17.11.1987', 'yyyy-MM-dd', 'cs.CZ', null); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2decimal() { doCompile("test_convertlib_str2decimal"); check("parsedDecimal1", new BigDecimal("100.13")); check("parsedDecimal2", new BigDecimal("123123123.123")); check("parsedDecimal3", new BigDecimal("-350000.01")); check("parsedDecimal4", new BigDecimal("1000000")); check("parsedDecimal5", new BigDecimal("1000000.99")); check("parsedDecimal6", new BigDecimal("123123123.123")); check("parsedDecimal7", new BigDecimal("5.01")); check("nullRet1", null); check("nullRet2", null); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); check("nullRet7", new BigDecimal("5.05")); // CLO-1614 check("nullRet8", new BigDecimal("5.05")); check("nullRet9", new BigDecimal("5.05")); check("nullRet10", new BigDecimal("5.05")); check("nullRet11", new BigDecimal("5.05")); check("nullRet12", new BigDecimal("5.05")); check("nullRet13", new BigDecimal("5.05")); check("nullRet14", new BigDecimal("5.05")); check("nullRet15", new BigDecimal("5.05")); check("nullRet16", new BigDecimal("5.05")); } public void test_convertlib_str2decimal_expect_result(){ try { doCompile("function integer transform(){decimal d = str2decimal(''); return 0;}","test_convertlib_str2decimal_expect_result"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK','#.#CZ'); return 0;}","test_convertlib_str2decimal_expect_result"); fail(); } catch (Exception e) { // do nothing } // CLO-1614 try { doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK',null); return 0;}","test_convertlib_str2decimal_expect_result"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK',null, null); return 0;}","test_convertlib_str2decimal_expect_result"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2double() { doCompile("test_convertlib_str2double"); check("parsedDouble1", 100.13); check("parsedDouble2", 123123123.123); check("parsedDouble3", -350000.01); check("nullRet1", null); check("nullRet2", null); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); check("nullRet7", 12.34d); // CLO-1614 check("nullRet8", 12.34d); check("nullRet9", 12.34d); check("nullRet10", 12.34d); check("nullRet11", 12.34d); check("nullRet12", 12.34d); check("nullRet13", 12.34d); check("nullRet14", 12.34d); check("nullRet15", 12.34d); } public void test_convertlib_str2double_expect_error(){ try { doCompile("function integer transform(){double d = str2double(''); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double d = str2double('text'); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double d = str2double('0.90c','#.# c'); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } // CLO-1614 try { doCompile("function integer transform(){double d = str2double('0.90c',null); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double d = str2double('0.90c', null); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double d = str2double('0.90c', null, null); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2integer() { doCompile("test_convertlib_str2integer"); check("parsedInteger1", 123456789); check("parsedInteger2", 123123); check("parsedInteger3", -350000); check("parsedInteger4", 419); check("nullRet1", 123); check("nullRet2", 123); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); check("nullRet7", null); check("nullRet8", null); check("nullRet9", null); // CLO-1614 // check("nullRet10", 123); // ambiguous check("nullRet11", 123); check("nullRet12", 123); check("nullRet13", 123); check("nullRet14", 123); check("nullRet15", 123); check("nullRet16", 123); check("nullRet17", 123); } public void test_convertlib_str2integer_expect_error(){ try { doCompile("function integer transform(){integer i = str2integer('abc'); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = str2integer(''); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = str2integer('123 mil', '###mil'); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; integer i = str2integer('123,1', s); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; integer i = str2integer('123,1', s, null); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = str2integer('1F', 2); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2long() { doCompile("test_convertlib_str2long"); check("parsedLong1", 1234567890123L); check("parsedLong2", 123123123456789L); check("parsedLong3", -350000L); check("parsedLong4", 133L); check("nullRet1", 123l); check("nullRet2", 123l); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); check("nullRet7", null); check("nullRet8", null); check("nullRet9", null); // CLO-1614 // check("nullRet10", 123l); // ambiguous check("nullRet11", 123l); check("nullRet12", 123l); check("nullRet13", 123l); check("nullRet14", 123l); check("nullRet15", 123l); check("nullRet16", 123l); check("nullRet17", 123l); } public void test_convertlib_str2long_expect_error(){ try { doCompile("function integer transform(){long i = str2long('abc'); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long(''); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long('13', '## bls'); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long('13', '## bls' , null); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long('13 L', null, 'cs.Cz'); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long('1A', 2); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_toString() { doCompile("test_convertlib_toString"); check("integerString", "10"); check("longString", "110654321874"); check("doubleString", "1.547874E-14"); check("decimalString", "-6847521431.1545874"); check("listString", "[not ALI A, not ALI B, not ALI D..., but, ALI H!]"); check("mapString", "{1=Testing, 2=makes, 3=me, 4=crazy :-)}"); String byteMapString = getVariable("byteMapString").toString(); assertTrue(byteMapString.contains("1=value1")); assertTrue(byteMapString.contains("2=value2")); String fieldByteMapString = getVariable("fieldByteMapString").toString(); assertTrue(fieldByteMapString.contains("key1=value1")); assertTrue(fieldByteMapString.contains("key2=value2")); check("byteListString", "[firstElement, secondElement]"); check("fieldByteListString", "[firstElement, secondElement]"); // CLO-1262 check("test_null_l", "null"); check("test_null_dec", "null"); check("test_null_d", "null"); check("test_null_i", "null"); } public void test_convertlib_str2byte() { doCompile("test_convertlib_str2byte"); checkArray("utf8Hello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("utf8Horse", new byte[] { 80, -59, -103, -61, -83, 108, 105, -59, -95, 32, -59, -66, 108, 117, -59, -91, 111, 117, -60, -115, 107, -61, -67, 32, 107, -59, -81, -59, -120, 32, 112, -60, -101, 108, 32, -60, -113, -61, -95, 98, 108, 115, 107, -61, -87, 32, -61, -77, 100, 121 }); checkArray("utf8Math", new byte[] { -62, -67, 32, -30, -123, -109, 32, -62, -68, 32, -30, -123, -107, 32, -30, -123, -103, 32, -30, -123, -101, 32, -30, -123, -108, 32, -30, -123, -106, 32, -62, -66, 32, -30, -123, -105, 32, -30, -123, -100, 32, -30, -123, -104, 32, -30, -126, -84, 32, -62, -78, 32, -62, -77, 32, -30, -128, -96, 32, -61, -105, 32, -30, -122, -112, 32, -30, -122, -110, 32, -30, -122, -108, 32, -30, -121, -110, 32, -30, -128, -90, 32, -30, -128, -80, 32, -50, -111, 32, -50, -110, 32, -30, -128, -109, 32, -50, -109, 32, -50, -108, 32, -30, -126, -84, 32, -50, -107, 32, -50, -106, 32, -49, -128, 32, -49, -127, 32, -49, -126, 32, -49, -125, 32, -49, -124, 32, -49, -123, 32, -49, -122, 32, -49, -121, 32, -49, -120, 32, -49, -119 }); checkArray("utf16Hello", new byte[] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 }); checkArray("utf16Horse", new byte[] { -2, -1, 0, 80, 1, 89, 0, -19, 0, 108, 0, 105, 1, 97, 0, 32, 1, 126, 0, 108, 0, 117, 1, 101, 0, 111, 0, 117, 1, 13, 0, 107, 0, -3, 0, 32, 0, 107, 1, 111, 1, 72, 0, 32, 0, 112, 1, 27, 0, 108, 0, 32, 1, 15, 0, -31, 0, 98, 0, 108, 0, 115, 0, 107, 0, -23, 0, 32, 0, -13, 0, 100, 0, 121 }); checkArray("utf16Math", new byte[] { -2, -1, 0, -67, 0, 32, 33, 83, 0, 32, 0, -68, 0, 32, 33, 85, 0, 32, 33, 89, 0, 32, 33, 91, 0, 32, 33, 84, 0, 32, 33, 86, 0, 32, 0, -66, 0, 32, 33, 87, 0, 32, 33, 92, 0, 32, 33, 88, 0, 32, 32, -84, 0, 32, 0, -78, 0, 32, 0, -77, 0, 32, 32, 32, 0, 32, 0, -41, 0, 32, 33, -112, 0, 32, 33, -110, 0, 32, 33, -108, 0, 32, 33, -46, 0, 32, 32, 38, 0, 32, 32, 48, 0, 32, 3, -111, 0, 32, 3, -110, 0, 32, 32, 19, 0, 32, 3, -109, 0, 32, 3, -108, 0, 32, 32, -84, 0, 32, 3, -107, 0, 32, 3, -106, 0, 32, 3, -64, 0, 32, 3, -63, 0, 32, 3, -62, 0, 32, 3, -61, 0, 32, 3, -60, 0, 32, 3, -59, 0, 32, 3, -58, 0, 32, 3, -57, 0, 32, 3, -56, 0, 32, 3, -55 }); checkArray("macHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("macHorse", new byte[] { 80, -34, -110, 108, 105, -28, 32, -20, 108, 117, -23, 111, 117, -117, 107, -7, 32, 107, -13, -53, 32, 112, -98, 108, 32, -109, -121, 98, 108, 115, 107, -114, 32, -105, 100, 121 }); checkArray("asciiHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("isoHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("isoHorse", new byte[] { 80, -8, -19, 108, 105, -71, 32, -66, 108, 117, -69, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 }); checkArray("cpHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("cpHorse", new byte[] { 80, -8, -19, 108, 105, -102, 32, -98, 108, 117, -99, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 }); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_str2byte_expect_error(){ try { doCompile("function integer transform(){byte b = str2byte('wallace',null); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = str2byte('wallace','knock'); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = str2byte('wallace',null); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_byte2str() { doCompile("test_convertlib_byte2str"); String hello = "Hello World!"; String horse = "Příliš žluťoučký kůň pěl ďáblské ódy"; String math = "½ ⅓ ¼ ⅕ ⅙ ⅛ ⅔ ⅖ ¾ ⅗ ⅜ ⅘ € ² ³ † × ← → ↔ ⇒ … ‰ Α Β – Γ Δ € Ε Ζ π ρ ς σ τ υ φ χ ψ ω"; check("utf8Hello", hello); check("utf8Horse", horse); check("utf8Math", math); check("utf16Hello", hello); check("utf16Horse", horse); check("utf16Math", math); check("macHello", hello); check("macHorse", horse); check("asciiHello", hello); check("isoHello", hello); check("isoHorse", horse); check("cpHello", hello); check("cpHorse", horse); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_byte2str_expect_error(){ try { doCompile("function integer transform(){string s = byte2str(null,null); return 0;}","test_convertlib_byte2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = byte2str(str2byte('hello', 'utf-8'),null); return 0;}","test_convertlib_byte2str_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_conditional_fail() { doCompile("test_conditional_fail"); check("result", 3); } public void test_expression_statement(){ // test case for issue 4174 doCompileExpectErrors("test_expression_statement", Arrays.asList("Syntax error, statement expected","Syntax error, statement expected")); } public void test_dictionary_read() { doCompile("test_dictionary_read"); check("s", "Verdon"); check("i", Integer.valueOf(211)); check("l", Long.valueOf(226)); check("d", BigDecimal.valueOf(239483061)); check("n", Double.valueOf(934.2)); check("a", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime()); check("b", true); byte[] y = (byte[]) getVariable("y"); assertEquals(10, y.length); assertEquals(89, y[9]); check("sNull", null); check("iNull", null); check("lNull", null); check("dNull", null); check("nNull", null); check("aNull", null); check("bNull", null); check("yNull", null); check("stringList", Arrays.asList("aa", "bb", null, "cc")); check("dateList", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000))); @SuppressWarnings("unchecked") List<byte[]> byteList = (List<byte[]>) getVariable("byteList"); assertDeepEquals(byteList, Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78})); } public void test_dictionary_write() { doCompile("test_dictionary_write"); assertEquals(832, graph.getDictionary().getValue("i") ); assertEquals("Guil", graph.getDictionary().getValue("s")); assertEquals(Long.valueOf(540), graph.getDictionary().getValue("l")); assertEquals(BigDecimal.valueOf(621), graph.getDictionary().getValue("d")); assertEquals(934.2, graph.getDictionary().getValue("n")); assertEquals(new GregorianCalendar(1992, GregorianCalendar.DECEMBER, 2).getTime(), graph.getDictionary().getValue("a")); assertEquals(true, graph.getDictionary().getValue("b")); byte[] y = (byte[]) graph.getDictionary().getValue("y"); assertEquals(2, y.length); assertEquals(18, y[0]); assertEquals(-94, y[1]); assertEquals(Arrays.asList("xx", null), graph.getDictionary().getValue("stringList")); assertEquals(Arrays.asList(new Date(98000), null, new Date(76000)), graph.getDictionary().getValue("dateList")); @SuppressWarnings("unchecked") List<byte[]> byteList = (List<byte[]>) graph.getDictionary().getValue("byteList"); assertDeepEquals(byteList, Arrays.asList(null, new byte[] {(byte) 0xAB, (byte) 0xCD}, new byte[] {(byte) 0xEF})); check("assignmentReturnValue", "Guil"); } public void test_dictionary_write_null() { doCompile("test_dictionary_write_null"); assertEquals(null, graph.getDictionary().getValue("s")); assertEquals(null, graph.getDictionary().getValue("sVerdon")); assertEquals(null, graph.getDictionary().getValue("i") ); assertEquals(null, graph.getDictionary().getValue("i211") ); assertEquals(null, graph.getDictionary().getValue("l")); assertEquals(null, graph.getDictionary().getValue("l452")); assertEquals(null, graph.getDictionary().getValue("d")); assertEquals(null, graph.getDictionary().getValue("d621")); assertEquals(null, graph.getDictionary().getValue("n")); assertEquals(null, graph.getDictionary().getValue("n9342")); assertEquals(null, graph.getDictionary().getValue("a")); assertEquals(null, graph.getDictionary().getValue("a1992")); assertEquals(null, graph.getDictionary().getValue("b")); assertEquals(null, graph.getDictionary().getValue("bTrue")); assertEquals(null, graph.getDictionary().getValue("y")); assertEquals(null, graph.getDictionary().getValue("yFib")); } public void test_dictionary_invalid_key(){ doCompileExpectErrors("test_dictionary_invalid_key", Arrays.asList("Dictionary entry 'invalid' does not exist")); } public void test_dictionary_string_to_int(){ doCompileExpectErrors("test_dictionary_string_to_int", Arrays.asList("Type mismatch: cannot convert from 'string' to 'integer'","Type mismatch: cannot convert from 'string' to 'integer'")); } public void test_utillib_sleep() { long time = System.currentTimeMillis(); doCompile("test_utillib_sleep"); long tmp = System.currentTimeMillis() - time; assertTrue("sleep() function didn't pause execution "+ tmp, tmp >= 1000); } public void test_utillib_random_uuid() { doCompile("test_utillib_random_uuid"); assertNotNull(getVariable("uuid")); } public void test_stringlib_randomString(){ doCompile("string test; function integer transform(){test = randomString(1,3); return 0;}","test_stringlib_randomString"); assertNotNull(getVariable("test")); } public void test_stringlib_randomString_expect_error(){ try { doCompile("function integer transform(){randomString(-5, 1); return 0;}","test_stringlib_randomString_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){randomString(15, 2); return 0;}","test_stringlib_randomString_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_validUrl() { doCompile("test_stringlib_url"); check("urlValid", Arrays.asList(true, true, false, true, false, true)); check("protocol", Arrays.asList("http", "https", null, "sandbox", null, "zip")); check("userInfo", Arrays.asList("", "chuck:norris", null, "", null, "")); check("host", Arrays.asList("example.com", "server.javlin.eu", null, "cloveretl.test.scenarios", null, "")); check("port", Arrays.asList(-1, 12345, -2, -1, -2, -1)); check("path", Arrays.asList("", "/backdoor/trojan.cgi", null, "/graph/UDR_FileURL_SFTP_OneGzipFileSpecified.grf", null, "(sftp://test:test@koule/home/test/data-in/file2.zip)")); check("query", Arrays.asList("", "hash=SHA560;god=yes", null, "", null, "")); check("ref", Arrays.asList("", "autodestruct", null, "", null, "innerfolder2/URLIn21.txt")); } public void test_stringlib_escapeUrl() { doCompile("test_stringlib_escapeUrl"); check("escaped", "http://example.com/foo%20bar%5E"); check("unescaped", "http://example.com/foo bar^"); } public void test_stringlib_escapeUrl_unescapeUrl_expect_error(){ //test: escape - empty string try { doCompile("string test; function integer transform() {test = escapeUrl(''); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: escape - null string try { doCompile("string test; function integer transform() {test = escapeUrl(null); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: unescape - empty string try { doCompile("string test; function integer transform() {test = unescapeUrl(''); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: unescape - null try { doCompile("string test; function integer transform() {test = unescapeUrl(null); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: escape - invalid URL try { doCompile("string test; function integer transform() {test = escapeUrl('somewhere over the rainbow'); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: unescpae - invalid URL try { doCompile("string test; function integer transform() {test = unescapeUrl('mister%20postman'); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_resolveParams() { doCompile("test_stringlib_resolveParams"); check("resultNoParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in"); check("resultFalseFalseParams", "Special character representing new line is: \\n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in"); check("resultTrueFalseParams", "Special character representing new line is: \n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in"); check("resultFalseTrueParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in"); check("resultTrueTrueParams", "Special character representing new line is: \n calling CTL function MESSAGE; $DATAIN_DIR=./data-in"); } public void test_utillib_getEnvironmentVariables() { doCompile("test_utillib_getEnvironmentVariables"); check("empty", false); check("ret1", null); // CLO-1700 // check("ret2", null); // check("ret3", null); } public void test_utillib_getJavaProperties() { String key1 = "my.testing.property"; String key2 = "my.testing.property2"; String value = "my value"; String value2; assertNull(System.getProperty(key1)); assertNull(System.getProperty(key2)); System.setProperty(key1, value); try { doCompile("test_utillib_getJavaProperties"); value2 = System.getProperty(key2); } finally { System.clearProperty(key1); assertNull(System.getProperty(key1)); System.clearProperty(key2); assertNull(System.getProperty(key2)); } check("java_specification_name", "Java Platform API Specification"); check("my_testing_property", value); assertEquals("my value 2", value2); check("ret1", null); // CLO-1700 // check("ret2", null); // check("ret3", null); } public void test_utillib_getParamValues() { doCompile("test_utillib_getParamValues"); Map<String, String> params = new HashMap<String, String>(); params.put("PROJECT", "."); params.put("DATAIN_DIR", "./data-in"); params.put("COUNT", "3"); params.put("NEWLINE", "\\n"); // special characters should NOT be resolved check("params", params); check("ret1", null); check("ret2", null); check("ret3", null); } public void test_utillib_getParamValue() { doCompile("test_utillib_getParamValue"); Map<String, String> params = new HashMap<String, String>(); params.put("PROJECT", "."); params.put("DATAIN_DIR", "./data-in"); params.put("COUNT", "3"); params.put("NEWLINE", "\\n"); // special characters should NOT be resolved params.put("NONEXISTING", null); check("params", params); check("ret1", null); check("ret2", null); } public void test_stringlib_getUrlParts() { doCompile("test_stringlib_getUrlParts"); List<Boolean> isUrl = Arrays.asList(true, true, true, true, false); List<String> path = Arrays.asList( "/users/a6/15e83578ad5cba95c442273ea20bfa/msf-183/out5.txt", "/data-in/fileOperation/input.txt", "/data/file.txt", "/data/file.txt", null); List<String> protocol = Arrays.asList("sftp", "sandbox", "ftp", "https", null); List<String> host = Arrays.asList( "ava-fileManipulator1-devel.getgooddata.com", "cloveretl.test.scenarios", "ftp.test.com", "www.test.com", null); List<Integer> port = Arrays.asList(-1, -1, 21, 80, -2); List<String> userInfo = Arrays.asList( "user%40gooddata.com:password", "", "test:test", "test:test", null); List<String> ref = Arrays.asList("", "", "", "", null); List<String> query = Arrays.asList("", "", "", "", null); check("isUrl", isUrl); check("path", path); check("protocol", protocol); check("host", host); check("port", port); check("userInfo", userInfo); check("ref", ref); check("query", query); check("isURL_empty", false); check("path_empty", null); check("protocol_empty", null); check("host_empty", null); check("port_empty", -2); check("userInfo_empty", null); check("ref_empty", null); check("query_empty", null); check("isURL_null", false); check("path_null", null); check("protocol_null", null); check("host_null", null); check("port_null", -2); check("userInfo_null", null); check("ref_null", null); check("query_empty", null); } public void test_utillib_iif() throws UnsupportedEncodingException{ doCompile("test_utillib_iif"); check("ret1", "Renektor"); Calendar cal = Calendar.getInstance(); cal.set(2005,10,12,0,0,0); cal.set(Calendar.MILLISECOND,0); check("ret2", cal.getTime()); checkArray("ret3", "Akali".getBytes("UTF-8")); check("ret4", 236); check("ret5", 78L); check("ret6", 78.2d); check("ret7", new BigDecimal("87.69")); check("ret8", true); } public void test_utillib_iif_expect_error(){ try { doCompile("function integer transform(){boolean b = null; string str = iif(b, 'Rammus', 'Sion'); return 0;}","test_utillib_iif_expect_error"); fail(); } catch (Exception e) { // do nothing } //CLO-1701 try { doCompile("function integer transform(){string str = iif(null, 'Rammus', 'Sion'); return 0;}","test_utillib_iif_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_utillib_isnull(){ doCompile("test_utillib_isnull"); check("ret1", false); check("ret2", true); check("ret3", false); check("ret4", true); check("ret5", false); check("ret6", true); check("ret7", false); check("ret8", true); check("ret9", false); check("ret10", true); check("ret11", false); check("ret12", true); check("ret13", false); check("ret14", true); check("ret15", false); check("ret16", true); check("ret17", false); check("ret18", true); check("ret19", true); } public void test_utillib_nvl() throws UnsupportedEncodingException{ doCompile("test_utillib_nvl"); check("ret1", "Fiora"); check("ret2", "Olaf"); checkArray("ret3", "Elise".getBytes("UTF-8")); checkArray("ret4", "Diana".getBytes("UTF-8")); Calendar cal = Calendar.getInstance(); cal.set(2005,4,13,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret5", cal.getTime()); cal.clear(); cal.set(2004,2,14,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret6", cal.getTime()); check("ret7", 7); check("ret8", 8); check("ret9", 111l); check("ret10", 112l); check("ret11", 10.1d); check("ret12", 10.2d); check("ret13", new BigDecimal("12.2")); check("ret14", new BigDecimal("12.3")); check("ret15", null); } public void test_utillib_nvl2() throws UnsupportedEncodingException{ doCompile("test_utillib_nvl2"); check("ret1", "Ahri"); check("ret2", "Galio"); checkArray("ret3", "Mordekaiser".getBytes("UTF-8")); checkArray("ret4", "Zed".getBytes("UTF-8")); Calendar cal = Calendar.getInstance(); cal.set(2010,4,18,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret5", cal.getTime()); cal.clear(); cal.set(2008,7,9,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret6", cal.getTime()); check("ret7", 11); check("ret8", 18); check("ret9", 20L); check("ret10", 23L); check("ret11", 15.2d); check("ret12", 89.3d); check("ret13", new BigDecimal("22.2")); check("ret14", new BigDecimal("55.5")); check("ret15", null); check("ret16", null); check("ret17", "Shaco"); check("ret18", 12); check("ret19", 18.1d); check("ret20", 15L); check("ret21", new BigDecimal("18.1")); } public void test_utillib_toAbsolutePath(){ doCompile("test_utillib_toAbsolutePath"); assertNotNull(getVariable("ret1")); assertNotNull(getVariable("ret2")); check("ret3", null); } public void test_utillib_toAbsolutePath_expect_error(){ try { doCompile("function integer transform(){string str = toAbsolutePath(null); return 0;}","test_utillib_toAbsolutePath_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; string str = toAbsolutePath(s); return 0;}","test_utillib_toAbsolutePath_expect_error"); fail(); } catch (Exception e) { // do nothing } } }
cloveretl.engine/test/org/jetel/ctl/CompilerTestCase.java
package org.jetel.ctl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TimeZone; import junit.framework.AssertionFailedError; import org.jetel.component.CTLRecordTransform; import org.jetel.component.RecordTransform; import org.jetel.data.DataField; import org.jetel.data.DataRecord; import org.jetel.data.DataRecordFactory; import org.jetel.data.SetVal; import org.jetel.data.lookup.LookupTable; import org.jetel.data.lookup.LookupTableFactory; import org.jetel.data.primitive.Decimal; import org.jetel.data.sequence.Sequence; import org.jetel.data.sequence.SequenceFactory; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.TransformException; import org.jetel.graph.ContextProvider; import org.jetel.graph.ContextProvider.Context; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataFieldContainerType; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataFieldType; import org.jetel.metadata.DataRecordMetadata; import org.jetel.test.CloverTestCase; import org.jetel.util.MiscUtils; import org.jetel.util.bytes.PackedDecimal; import org.jetel.util.crypto.Base64; import org.jetel.util.crypto.Digest; import org.jetel.util.crypto.Digest.DigestType; import org.jetel.util.primitive.TypedProperties; import org.jetel.util.string.StringUtils; import org.joda.time.DateTime; import org.joda.time.Years; public abstract class CompilerTestCase extends CloverTestCase { // ---------- RECORD NAMES ----------- protected static final String INPUT_1 = "firstInput"; protected static final String INPUT_2 = "secondInput"; protected static final String INPUT_3 = "thirdInput"; protected static final String INPUT_4 = "multivalueInput"; protected static final String OUTPUT_1 = "firstOutput"; protected static final String OUTPUT_2 = "secondOutput"; protected static final String OUTPUT_3 = "thirdOutput"; protected static final String OUTPUT_4 = "fourthOutput"; protected static final String OUTPUT_5 = "firstMultivalueOutput"; protected static final String OUTPUT_6 = "secondMultivalueOutput"; protected static final String OUTPUT_7 = "thirdMultivalueOutput"; protected static final String LOOKUP = "lookupMetadata"; protected static final String NAME_VALUE = " HELLO "; protected static final Double AGE_VALUE = 20.25; protected static final String CITY_VALUE = "Chong'La"; protected static final Date BORN_VALUE; protected static final Long BORN_MILLISEC_VALUE; static { Calendar c = Calendar.getInstance(); c.set(2008, 12, 25, 13, 25, 55); c.set(Calendar.MILLISECOND, 333); BORN_VALUE = c.getTime(); BORN_MILLISEC_VALUE = c.getTimeInMillis(); } protected static final Integer VALUE_VALUE = Integer.MAX_VALUE - 10; protected static final Boolean FLAG_VALUE = true; protected static final byte[] BYTEARRAY_VALUE = "Abeceda zedla deda".getBytes(); protected static final BigDecimal CURRENCY_VALUE = new BigDecimal("133.525"); protected static final int DECIMAL_PRECISION = 7; protected static final int DECIMAL_SCALE = 3; protected static final int NORMALIZE_RETURN_OK = 0; public static final int DECIMAL_MAX_PRECISION = 32; public static final MathContext MAX_PRECISION = new MathContext(DECIMAL_MAX_PRECISION,RoundingMode.DOWN); /** Flag to trigger Java compilation */ private boolean compileToJava; protected DataRecord[] inputRecords; protected DataRecord[] outputRecords; protected TransformationGraph graph; public CompilerTestCase(boolean compileToJava) { this.compileToJava = compileToJava; } /** * Method to execute tested CTL code in a way specific to testing scenario. * * Assumes that * {@link #graph}, {@link #inputRecords} and {@link #outputRecords} * have already been set. * * @param compiler */ public abstract void executeCode(ITLCompiler compiler); /** * Method which provides access to specified global variable * * @param varName * global variable to be accessed * @return * */ protected abstract Object getVariable(String varName); protected void check(String varName, Object expectedResult) { assertEquals(varName, expectedResult, getVariable(varName)); } protected void checkEqualValue(String varName, Object expectedResult) { assertTrue(varName, ((Comparable)expectedResult).compareTo(getVariable(varName))==0); } protected void checkEquals(String varName1, String varName2) { assertEquals("Comparing " + varName1 + " and " + varName2 + " : ", getVariable(varName1), getVariable(varName2)); } protected void checkNull(String varName) { assertNull(getVariable(varName)); } private void checkArray(String varName, byte[] expected) { byte[] actual = (byte[]) getVariable(varName); assertTrue("Arrays do not match; expected: " + byteArrayAsString(expected) + " but was " + byteArrayAsString(actual), Arrays.equals(actual, expected)); } private static String byteArrayAsString(byte[] array) { final StringBuilder sb = new StringBuilder("["); for (final byte b : array) { sb.append(b); sb.append(", "); } sb.delete(sb.length() - 2, sb.length()); sb.append(']'); return sb.toString(); } @Override protected void setUp() { // set default locale to English to prevent various parsing errors Locale.setDefault(Locale.ENGLISH); initEngine(); } @Override protected void tearDown() throws Exception { super.tearDown(); inputRecords = null; outputRecords = null; graph = null; } protected TransformationGraph createEmptyGraph() { return new TransformationGraph(); } protected TransformationGraph createDefaultGraph() { TransformationGraph g = createEmptyGraph(); // set the context URL, so that imports can be used g.getRuntimeContext().setContextURL(CompilerTestCase.class.getResource(".")); final HashMap<String, DataRecordMetadata> metadataMap = new HashMap<String, DataRecordMetadata>(); metadataMap.put(INPUT_1, createDefaultMetadata(INPUT_1)); metadataMap.put(INPUT_2, createDefaultMetadata(INPUT_2)); metadataMap.put(INPUT_3, createDefaultMetadata(INPUT_3)); metadataMap.put(INPUT_4, createDefaultMultivalueMetadata(INPUT_4)); metadataMap.put(OUTPUT_1, createDefaultMetadata(OUTPUT_1)); metadataMap.put(OUTPUT_2, createDefaultMetadata(OUTPUT_2)); metadataMap.put(OUTPUT_3, createDefaultMetadata(OUTPUT_3)); metadataMap.put(OUTPUT_4, createDefault1Metadata(OUTPUT_4)); metadataMap.put(OUTPUT_5, createDefaultMultivalueMetadata(OUTPUT_5)); metadataMap.put(OUTPUT_6, createDefaultMultivalueMetadata(OUTPUT_6)); metadataMap.put(OUTPUT_7, createDefaultMultivalueMetadata(OUTPUT_7)); metadataMap.put(LOOKUP, createDefaultMetadata(LOOKUP)); g.addDataRecordMetadata(metadataMap); g.addSequence(createDefaultSequence(g, "TestSequence")); g.addLookupTable(createDefaultLookup(g, "TestLookup")); Properties properties = new Properties(); properties.put("PROJECT", "."); properties.put("DATAIN_DIR", "${PROJECT}/data-in"); properties.put("COUNT", "`1+2`"); properties.put("NEWLINE", "\\n"); g.getGraphParameters().setProperties(properties); initDefaultDictionary(g); return g; } private void initDefaultDictionary(TransformationGraph g) { try { g.getDictionary().init(); g.getDictionary().setValue("s", "string", null); g.getDictionary().setValue("i", "integer", null); g.getDictionary().setValue("l", "long", null); g.getDictionary().setValue("d", "decimal", null); g.getDictionary().setValue("n", "number", null); g.getDictionary().setValue("a", "date", null); g.getDictionary().setValue("b", "boolean", null); g.getDictionary().setValue("y", "byte", null); g.getDictionary().setValue("i211", "integer", new Integer(211)); g.getDictionary().setValue("sVerdon", "string", "Verdon"); g.getDictionary().setValue("l452", "long", new Long(452)); g.getDictionary().setValue("d621", "decimal", new BigDecimal(621)); g.getDictionary().setValue("n9342", "number", new Double(934.2)); g.getDictionary().setValue("a1992", "date", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime()); g.getDictionary().setValue("bTrue", "boolean", Boolean.TRUE); g.getDictionary().setValue("yFib", "byte", new byte[]{1,2,3,5,8,13,21,34,55,89} ); g.getDictionary().setValue("stringList", "list", Arrays.asList("aa", "bb", null, "cc")); g.getDictionary().setContentType("stringList", "string"); g.getDictionary().setValue("dateList", "list", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000))); g.getDictionary().setContentType("dateList", "date"); g.getDictionary().setValue("byteList", "list", Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78})); g.getDictionary().setContentType("byteList", "byte"); } catch (ComponentNotReadyException e) { throw new RuntimeException("Error init default dictionary", e); } } protected Sequence createDefaultSequence(TransformationGraph graph, String name) { Sequence seq = SequenceFactory.createSequence(graph, "PRIMITIVE_SEQUENCE", new Object[] { "Sequence0", graph, name }, new Class[] { String.class, TransformationGraph.class, String.class }); try { seq.checkConfig(new ConfigurationStatus()); seq.init(); } catch (ComponentNotReadyException e) { throw new RuntimeException(e); } return seq; } /** * Creates default lookup table of type SimpleLookupTable with 4 records using default metadata and a composite * lookup key Name+Value. Use field City for testing response. * * @param graph * @param name * @return */ protected LookupTable createDefaultLookup(TransformationGraph graph, String name) { final TypedProperties props = new TypedProperties(); props.setProperty("id", "LookupTable0"); props.setProperty("type", "simpleLookup"); props.setProperty("metadata", LOOKUP); props.setProperty("key", "Name;Value"); props.setProperty("name", name); props.setProperty("keyDuplicates", "true"); /* * The test lookup table is populated from file TestLookup.dat. Alternatively uncomment the populating code * below, however this will most probably break down test_lookup() because free() will wipe away all data and * noone will restore them */ URL dataFile = getClass().getSuperclass().getResource("TestLookup.dat"); if (dataFile == null) { throw new RuntimeException("Unable to populate testing lookup table. File 'TestLookup.dat' not found by classloader"); } props.setProperty("fileURL", dataFile.getFile()); LookupTableFactory.init(); LookupTable lkp = LookupTableFactory.createLookupTable(props); lkp.setGraph(graph); try { lkp.checkConfig(new ConfigurationStatus()); lkp.init(); lkp.preExecute(); } catch (ComponentNotReadyException ex) { throw new RuntimeException(ex); } // ********* POPULATING CODE ************* /*DataRecord lkpRecord = createEmptyRecord(createDefaultMetadata("lookupResponse")); lkpRecord.getField("Name").setValue("Alpha"); lkpRecord.getField("Value").setValue(1); lkpRecord.getField("City").setValue("Andorra la Vella"); lkp.put(lkpRecord); lkpRecord.getField("Name").setValue("Bravo"); lkpRecord.getField("Value").setValue(2); lkpRecord.getField("City").setValue("Bruxelles"); lkp.put(lkpRecord); // duplicate entry lkpRecord.getField("Name").setValue("Charlie"); lkpRecord.getField("Value").setValue(3); lkpRecord.getField("City").setValue("Chamonix"); lkp.put(lkpRecord); lkpRecord.getField("Name").setValue("Charlie"); lkpRecord.getField("Value").setValue(3); lkpRecord.getField("City").setValue("Chomutov"); lkp.put(lkpRecord);*/ // ************ END OF POPULATING CODE ************ return lkp; } /** * Creates records with default structure * * @param name * name for the record to use * @return metadata with default structure */ protected DataRecordMetadata createDefaultMetadata(String name) { DataRecordMetadata ret = new DataRecordMetadata(name); ret.addField(new DataFieldMetadata("Name", DataFieldType.STRING, "|")); ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|")); ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|")); DataFieldMetadata dateField = new DataFieldMetadata("Born", DataFieldType.DATE, "|"); dateField.setFormatStr("yyyy-MM-dd HH:mm:ss"); ret.addField(dateField); ret.addField(new DataFieldMetadata("BornMillisec", DataFieldType.LONG, "|")); ret.addField(new DataFieldMetadata("Value", DataFieldType.INTEGER, "|")); ret.addField(new DataFieldMetadata("Flag", DataFieldType.BOOLEAN, "|")); ret.addField(new DataFieldMetadata("ByteArray", DataFieldType.BYTE, "|")); DataFieldMetadata decimalField = new DataFieldMetadata("Currency", DataFieldType.DECIMAL, "\n"); decimalField.setProperty(DataFieldMetadata.LENGTH_ATTR, String.valueOf(DECIMAL_PRECISION)); decimalField.setProperty(DataFieldMetadata.SCALE_ATTR, String.valueOf(DECIMAL_SCALE)); ret.addField(decimalField); return ret; } /** * Creates records with default structure * * @param name * name for the record to use * @return metadata with default structure */ protected DataRecordMetadata createDefault1Metadata(String name) { DataRecordMetadata ret = new DataRecordMetadata(name); ret.addField(new DataFieldMetadata("Field1", DataFieldType.STRING, "|")); ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|")); ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|")); return ret; } /** * Creates records with default structure * containing multivalue fields. * * @param name * name for the record to use * @return metadata with default structure */ protected DataRecordMetadata createDefaultMultivalueMetadata(String name) { DataRecordMetadata ret = new DataRecordMetadata(name); DataFieldMetadata stringListField = new DataFieldMetadata("stringListField", DataFieldType.STRING, "|"); stringListField.setContainerType(DataFieldContainerType.LIST); ret.addField(stringListField); DataFieldMetadata dateField = new DataFieldMetadata("dateField", DataFieldType.DATE, "|"); ret.addField(dateField); DataFieldMetadata byteField = new DataFieldMetadata("byteField", DataFieldType.BYTE, "|"); ret.addField(byteField); DataFieldMetadata dateListField = new DataFieldMetadata("dateListField", DataFieldType.DATE, "|"); dateListField.setContainerType(DataFieldContainerType.LIST); ret.addField(dateListField); DataFieldMetadata byteListField = new DataFieldMetadata("byteListField", DataFieldType.BYTE, "|"); byteListField.setContainerType(DataFieldContainerType.LIST); ret.addField(byteListField); DataFieldMetadata stringField = new DataFieldMetadata("stringField", DataFieldType.STRING, "|"); ret.addField(stringField); DataFieldMetadata integerMapField = new DataFieldMetadata("integerMapField", DataFieldType.INTEGER, "|"); integerMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(integerMapField); DataFieldMetadata stringMapField = new DataFieldMetadata("stringMapField", DataFieldType.STRING, "|"); stringMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(stringMapField); DataFieldMetadata dateMapField = new DataFieldMetadata("dateMapField", DataFieldType.DATE, "|"); dateMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(dateMapField); DataFieldMetadata byteMapField = new DataFieldMetadata("byteMapField", DataFieldType.BYTE, "|"); byteMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(byteMapField); DataFieldMetadata integerListField = new DataFieldMetadata("integerListField", DataFieldType.INTEGER, "|"); integerListField.setContainerType(DataFieldContainerType.LIST); ret.addField(integerListField); DataFieldMetadata decimalListField = new DataFieldMetadata("decimalListField", DataFieldType.DECIMAL, "|"); decimalListField.setContainerType(DataFieldContainerType.LIST); ret.addField(decimalListField); DataFieldMetadata decimalMapField = new DataFieldMetadata("decimalMapField", DataFieldType.DECIMAL, "|"); decimalMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(decimalMapField); return ret; } /** * Creates new record with specified metadata and sets its field to default values. The record structure will be * created by {@link #createDefaultMetadata(String)} * * @param dataRecordMetadata * metadata to use * @return record initialized to default values */ protected DataRecord createDefaultMultivalueRecord(DataRecordMetadata dataRecordMetadata) { final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata); ret.init(); for (int i = 0; i < ret.getNumFields(); i++) { DataField field = ret.getField(i); DataFieldMetadata fieldMetadata = field.getMetadata(); switch (fieldMetadata.getContainerType()) { case SINGLE: switch (fieldMetadata.getDataType()) { case STRING: field.setValue("John"); break; case DATE: field.setValue(new Date(10000)); break; case BYTE: field.setValue(new byte[] { 0x12, 0x34, 0x56, 0x78 } ); break; default: throw new UnsupportedOperationException("Not implemented."); } break; case LIST: { List<Object> value = new ArrayList<Object>(); switch (fieldMetadata.getDataType()) { case STRING: value.addAll(Arrays.asList("John", "Doe", "Jersey")); break; case INTEGER: value.addAll(Arrays.asList(123, 456, 789)); break; case DATE: value.addAll(Arrays.asList(new Date (12000), new Date(34000))); break; case BYTE: value.addAll(Arrays.asList(new byte[] {0x12, 0x34}, new byte[] {0x56, 0x78})); break; case DECIMAL: value.addAll(Arrays.asList(12.34, 56.78)); break; default: throw new UnsupportedOperationException("Not implemented."); } field.setValue(value); } break; case MAP: { Map<String, Object> value = new HashMap<String, Object>(); switch (fieldMetadata.getDataType()) { case STRING: value.put("firstName", "John"); value.put("lastName", "Doe"); value.put("address", "Jersey"); break; case INTEGER: value.put("count", 123); value.put("max", 456); value.put("sum", 789); break; case DATE: value.put("before", new Date (12000)); value.put("after", new Date(34000)); break; case BYTE: value.put("hash", new byte[] {0x12, 0x34}); value.put("checksum", new byte[] {0x56, 0x78}); break; case DECIMAL: value.put("asset", 12.34); value.put("liability", 56.78); break; default: throw new UnsupportedOperationException("Not implemented."); } field.setValue(value); } break; default: throw new IllegalArgumentException(fieldMetadata.getContainerType().toString()); } } return ret; } /** * Creates new record with specified metadata and sets its field to default values. The record structure will be * created by {@link #createDefaultMetadata(String)} * * @param dataRecordMetadata * metadata to use * @return record initialized to default values */ protected DataRecord createDefaultRecord(DataRecordMetadata dataRecordMetadata) { final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata); ret.init(); SetVal.setString(ret, "Name", NAME_VALUE); SetVal.setDouble(ret, "Age", AGE_VALUE); SetVal.setString(ret, "City", CITY_VALUE); SetVal.setDate(ret, "Born", BORN_VALUE); SetVal.setLong(ret, "BornMillisec", BORN_MILLISEC_VALUE); SetVal.setInt(ret, "Value", VALUE_VALUE); SetVal.setValue(ret, "Flag", FLAG_VALUE); SetVal.setValue(ret, "ByteArray", BYTEARRAY_VALUE); SetVal.setValue(ret, "Currency", CURRENCY_VALUE); return ret; } /** * Allocates new records with structure prescribed by metadata and sets all its fields to <code>null</code> * * @param metadata * structure to use * @return empty record */ protected DataRecord createEmptyRecord(DataRecordMetadata metadata) { DataRecord ret = DataRecordFactory.newRecord(metadata); ret.init(); for (int i = 0; i < ret.getNumFields(); i++) { SetVal.setNull(ret, i); } return ret; } /** * Executes the code using the default graph and records. */ protected void doCompile(String expStr, String testIdentifier) { TransformationGraph graph = createDefaultGraph(); DataRecord[] inRecords = new DataRecord[] { createDefaultRecord(graph.getDataRecordMetadata(INPUT_1)), createDefaultRecord(graph.getDataRecordMetadata(INPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(INPUT_3)), createDefaultMultivalueRecord(graph.getDataRecordMetadata(INPUT_4)) }; DataRecord[] outRecords = new DataRecord[] { createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_1)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_3)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_4)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_5)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_6)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_7)) }; doCompile(expStr, testIdentifier, graph, inRecords, outRecords); } /** * This method should be used to execute a test with a custom graph and custom input and output records. * * To execute a test with the default graph, * use {@link #doCompile(String)} * or {@link #doCompile(String, String)} instead. * * @param expStr * @param testIdentifier * @param graph * @param inRecords * @param outRecords */ protected void doCompile(String expStr, String testIdentifier, TransformationGraph graph, DataRecord[] inRecords, DataRecord[] outRecords) { this.graph = graph; this.inputRecords = inRecords; this.outputRecords = outRecords; // prepend the compilation mode prefix if (compileToJava) { expStr = "//#CTL2:COMPILE\n" + expStr; } print_code(expStr); DataRecordMetadata[] inMetadata = new DataRecordMetadata[inRecords.length]; for (int i = 0; i < inRecords.length; i++) { inMetadata[i] = inRecords[i].getMetadata(); } DataRecordMetadata[] outMetadata = new DataRecordMetadata[outRecords.length]; for (int i = 0; i < outRecords.length; i++) { outMetadata[i] = outRecords[i].getMetadata(); } ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8"); // *** NOTE: please don't remove this commented code. It is used for debugging // *** Uncomment the code to get the compiled Java code during test execution. // *** Please don't commit this code uncommited. // try { // System.out.println(compiler.convertToJava(expStr, CTLRecordTransform.class, testIdentifier)); // } catch (ErrorMessageException e) { // System.out.println("Error parsing CTL code. Unable to output Java translation."); // } List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier); printMessages(messages); if (compiler.errorCount() > 0) { throw new AssertionFailedError("Error in execution. Check standard output for details."); } // *** NOTE: please don't remove this commented code. It is used for debugging // *** Uncomment the code to get the compiled Java code during test execution. // *** Please don't commit this code uncommited. // CLVFStart parseTree = compiler.getStart(); // parseTree.dump(""); executeCode(compiler); } protected void doCompileExpectError(String expStr, String testIdentifier, List<String> errCodes) { graph = createDefaultGraph(); DataRecordMetadata[] inMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(INPUT_1), graph.getDataRecordMetadata(INPUT_2), graph.getDataRecordMetadata(INPUT_3) }; DataRecordMetadata[] outMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(OUTPUT_1), graph.getDataRecordMetadata(OUTPUT_2), graph.getDataRecordMetadata(OUTPUT_3), graph.getDataRecordMetadata(OUTPUT_4) }; // prepend the compilation mode prefix if (compileToJava) { expStr = "//#CTL2:COMPILE\n" + expStr; } print_code(expStr); ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8"); List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier); printMessages(messages); if (compiler.errorCount() == 0) { throw new AssertionFailedError("No errors in parsing. Expected " + errCodes.size() + " errors."); } if (compiler.errorCount() != errCodes.size()) { throw new AssertionFailedError(compiler.errorCount() + " errors in code, but expected " + errCodes.size() + " errors."); } Iterator<String> it = errCodes.iterator(); for (ErrorMessage errorMessage : compiler.getDiagnosticMessages()) { String expectedError = it.next(); if (!expectedError.equals(errorMessage.getErrorMessage())) { throw new AssertionFailedError("Error : \'" + compiler.getDiagnosticMessages().get(0).getErrorMessage() + "\', but expected: \'" + expectedError + "\'"); } } // CLVFStart parseTree = compiler.getStart(); // parseTree.dump(""); // executeCode(compiler); } protected void doCompileExpectError(String testIdentifier, String errCode) { doCompileExpectErrors(testIdentifier, Arrays.asList(errCode)); } protected void doCompileExpectErrors(String testIdentifier, List<String> errCodes) { URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl"); if (importLoc == null) { throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found"); } final StringBuilder sourceCode = new StringBuilder(); String line = null; try { BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream())); while ((line = rd.readLine()) != null) { sourceCode.append(line).append("\n"); } rd.close(); } catch (IOException e) { throw new RuntimeException("I/O error occured when reading source file", e); } doCompileExpectError(sourceCode.toString(), testIdentifier, errCodes); } /** * Method loads tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should * be stored in the same directory as this class. * * @param Test * identifier defining CTL file to load code from */ protected String loadSourceCode(String testIdentifier) { URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl"); if (importLoc == null) { throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found"); } final StringBuilder sourceCode = new StringBuilder(); String line = null; try { BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream())); while ((line = rd.readLine()) != null) { sourceCode.append(line).append("\n"); } rd.close(); } catch (IOException e) { throw new RuntimeException("I/O error occured when reading source file", e); } return sourceCode.toString(); } /** * Method loads and compiles tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should * be stored in the same directory as this class. * * The default graph and records are used for the execution. * * @param Test * identifier defining CTL file to load code from */ protected void doCompile(String testIdentifier) { String sourceCode = loadSourceCode(testIdentifier); doCompile(sourceCode, testIdentifier); } protected void printMessages(List<ErrorMessage> diagnosticMessages) { for (ErrorMessage e : diagnosticMessages) { System.out.println(e); } } /** * Compares two records if they have the same number of fields and identical values in their fields. Does not * consider (or examine) metadata. * * @param lhs * @param rhs * @return true if records have the same number of fields and the same values in them */ protected static boolean recordEquals(DataRecord lhs, DataRecord rhs) { if (lhs == rhs) return true; if (rhs == null) return false; if (lhs == null) { return false; } if (lhs.getNumFields() != rhs.getNumFields()) { return false; } for (int i = 0; i < lhs.getNumFields(); i++) { if (lhs.getField(i).isNull()) { if (!rhs.getField(i).isNull()) { return false; } } else if (!lhs.getField(i).equals(rhs.getField(i))) { return false; } } return true; } public void print_code(String text) { String[] lines = text.split("\n"); System.out.println("\t: 1 2 3 4 5 "); System.out.println("\t:12345678901234567890123456789012345678901234567890123456789"); for (int i = 0; i < lines.length; i++) { System.out.println((i + 1) + "\t:" + lines[i]); } } //----------------------------- TESTS ----------------------------- @SuppressWarnings("unchecked") public void test_operators_unary_record_allowed() { doCompile("test_operators_unary_record_allowed"); check("value", Arrays.asList(14, 16, 16, 65, 63, 63)); check("bornMillisec", Arrays.asList(14L, 16L, 16L, 65L, 63L, 63L)); List<Double> actualAge = (List<Double>) getVariable("age"); double[] expectedAge = {14.123, 16.123, 16.123, 65.789, 63.789, 63.789}; for (int i = 0; i < actualAge.size(); i++) { assertEquals("age[" + i + "]", expectedAge[i], actualAge.get(i), 0.0001); } check("currency", Arrays.asList( new BigDecimal(BigInteger.valueOf(12500), 3), new BigDecimal(BigInteger.valueOf(14500), 3), new BigDecimal(BigInteger.valueOf(14500), 3), new BigDecimal(BigInteger.valueOf(65432), 3), new BigDecimal(BigInteger.valueOf(63432), 3), new BigDecimal(BigInteger.valueOf(63432), 3) )); } @SuppressWarnings("unchecked") public void test_dynamiclib_compare() { doCompile("test_dynamic_compare"); String varName = "compare"; List<Integer> compareResult = (List<Integer>) getVariable(varName); for (int i = 0; i < compareResult.size(); i++) { if ((i % 3) == 0) { assertTrue(varName + "[" + i + "]", compareResult.get(i) > 0); } else if ((i % 3) == 1) { assertEquals(varName + "[" + i + "]", Integer.valueOf(0), compareResult.get(i)); } else if ((i % 3) == 2) { assertTrue(varName + "[" + i + "]", compareResult.get(i) < 0); } } varName = "compareBooleans"; compareResult = (List<Integer>) getVariable(varName); assertEquals(varName + "[0]", Integer.valueOf(0), compareResult.get(0)); assertTrue(varName + "[1]", compareResult.get(1) > 0); assertTrue(varName + "[2]", compareResult.get(2) < 0); assertEquals(varName + "[3]", Integer.valueOf(0), compareResult.get(3)); } public void test_dynamiclib_compare_expect_error(){ try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.0; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, 'Flagxx', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.0; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, 'Flag', myRec2, 'Flagxx'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = null; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, 'Flag', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = null; " + "firstOutput myRec2; myRec2 = null;" + "integer i = compare(myRec, 'Flag', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.1; " + "firstOutput myRec2; myRec2 = null;" + "integer i = compare(myRec, 'Flag', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "$out.0.Flag = true; " + "$out.1.Age = 11;" + "integer i = compare($out.0, 'Flag', $out.1, 'Age'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.0; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, -1, myRec2, -1 ); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.0; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, 2, myRec2, 2 ); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "$out.0.8 = 12.4d; " + "$out.1.8 = 12.5d;" + "integer i = compare($out.0, 9, $out.1, 9 ); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "$out.0.0 = null; " + "$out.1.0 = null;" + "integer i = compare($out.0, 0, $out.1, 0 ); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } } private void test_dynamic_get_set_loop(String testIdentifier) { doCompile(testIdentifier); check("recordLength", 9); check("value", Arrays.asList(654321, 777777, 654321, 654323, 123456, 112567, 112233)); check("type", Arrays.asList("string", "number", "string", "date", "long", "integer", "boolean", "byte", "decimal")); check("asString", Arrays.asList("1000", "1001.0", "1002", "Thu Jan 01 01:00:01 CET 1970", "1004", "1005", "true", null, "1008.000")); check("isNull", Arrays.asList(false, false, false, false, false, false, false, true, false)); check("fieldName", Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency")); Integer[] indices = new Integer[9]; for (int i = 0; i < indices.length; i++) { indices[i] = i; } check("fieldIndex", Arrays.asList(indices)); // check dynamic write and read with all data types check("booleanVar", true); assertTrue("byteVar", Arrays.equals(new BigInteger("1234567890abcdef", 16).toByteArray(), (byte[]) getVariable("byteVar"))); check("decimalVar", new BigDecimal(BigInteger.valueOf(1000125), 3)); check("integerVar", 1000); check("longVar", 1000000000000L); check("numberVar", 1000.5); check("stringVar", "hello"); check("dateVar", new Date(5000)); // null value Boolean[] someValue = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()]; Arrays.fill(someValue, Boolean.FALSE); check("someValue", Arrays.asList(someValue)); Boolean[] nullValue = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()]; Arrays.fill(nullValue, Boolean.TRUE); check("nullValue", Arrays.asList(nullValue)); String[] asString2 = new String[graph.getDataRecordMetadata(INPUT_1).getNumFields()]; check("asString2", Arrays.asList(asString2)); Boolean[] isNull2 = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()]; Arrays.fill(isNull2, Boolean.TRUE); check("isNull2", Arrays.asList(isNull2)); } public void test_dynamic_get_set_loop() { test_dynamic_get_set_loop("test_dynamic_get_set_loop"); } public void test_dynamic_get_set_loop_alternative() { test_dynamic_get_set_loop("test_dynamic_get_set_loop_alternative"); } public void test_dynamic_invalid() { doCompileExpectErrors("test_dynamic_invalid", Arrays.asList( "Input record cannot be assigned to", "Input record cannot be assigned to" )); } public void test_dynamiclib_getBoolValue(){ doCompile("test_dynamiclib_getBoolValue"); check("ret1", true); check("ret2", true); check("ret3", false); check("ret4", false); check("ret5", null); check("ret6", null); } public void test_dynamiclib_getBoolValue_expect_error(){ try { doCompile("function integer transform(){boolean b = getBoolValue($in.0, 2);return 0;}","test_dynamiclib_getBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){boolean b = getBoolValue($in.0, 'Age');return 0;}","test_dynamiclib_getBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi; fi = null; boolean b = getBoolValue(fi, 6); return 0;}","test_dynamiclib_getBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi; fi = null; boolean b = getBoolValue(fi, 'Flag'); return 0;}","test_dynamiclib_getBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getByteValue(){ doCompile("test_dynamiclib_getByteValue"); checkArray("ret1",CompilerTestCase.BYTEARRAY_VALUE); checkArray("ret2",CompilerTestCase.BYTEARRAY_VALUE); check("ret3", null); check("ret4", null); } public void test_dynamiclib_getByteValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; byte b = getByteValue(fi,7); return 0;}","test_dynamiclib_getByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; byte b = fi.getByteValue('ByteArray'); return 0;}","test_dynamiclib_getByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = $in.0.getByteValue('Age'); return 0;}","test_dynamiclib_getByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = getByteValue($in.0, 0); return 0;}","test_dynamiclib_getByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getDateValue(){ doCompile("test_dynamiclib_getDateValue"); check("ret1", CompilerTestCase.BORN_VALUE); check("ret2", CompilerTestCase.BORN_VALUE); check("ret3", null); check("ret4", null); } public void test_dynamiclib_getDateValue_expect_error(){ try { doCompile("function integer transform(){date d = getDateValue($in.0,1); return 0;}","test_dynamiclib_getDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = getDateValue($in.0,'Age'); return 0;}","test_dynamiclib_getDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; date d = getDateValue(null,'Born'); return 0;}","test_dynamiclib_getDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; date d = getDateValue(null,3); return 0;}","test_dynamiclib_getDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getDecimalValue(){ doCompile("test_dynamiclib_getDecimalValue"); check("ret1", CompilerTestCase.CURRENCY_VALUE); check("ret2", CompilerTestCase.CURRENCY_VALUE); check("ret3", null); check("ret4", null); } public void test_dynamiclib_getDecimalValue_expect_error(){ try { doCompile("function integer transform(){decimal d = getDecimalValue($in.0, 1); return 0;}","test_dynamiclib_getDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal d = getDecimalValue($in.0, 'Age'); return 0;}","test_dynamiclib_getDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; decimal d = getDecimalValue(fi,8); return 0;}","test_dynamiclib_getDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; decimal d = getDecimalValue(fi,'Currency'); return 0;}","test_dynamiclib_getDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getFieldIndex(){ doCompile("test_dynamiclib_getFieldIndex"); check("ret1", 1); check("ret2", 1); check("ret3", -1); } public void test_dynamiclib_getFieldIndex_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; integer int = fi.getFieldIndex('Age'); return 0;}","test_dynamiclib_getFieldIndex_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getFieldLabel(){ doCompile("test_dynamiclib_getFieldLabel"); check("ret1", "Age"); check("ret2", "Name"); check("ret3", "Age"); check("ret4", "Value"); } public void test_dynamiclib_getFieldLabel_expect_error(){ try { doCompile("function integer transform(){string name = getFieldLabel($in.0, -5);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string name = getFieldLabel($in.0, 12);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string name = fi.getFieldLabel(2);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string name = fi.getFieldLabel('Age');return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string name = fi.getFieldLabel('');return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; firstInput fi = null; string name = fi.getFieldLabel(s);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer s = null; firstInput fi = null; string name = fi.getFieldLabel(s);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string name = getFieldLabel($in.0, 'Tristana');return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; string name = getFieldLabel($in.0, s);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer s = null; string name = getFieldLabel($in.0, s);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string name = getFieldLabel($in.0, '');return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getFieldName(){ doCompile("test_dynamiclib_getFieldName"); check("ret1", "Age"); check("ret2", "Name"); } public void test_dynamiclib_getFieldName_expect_error(){ try { doCompile("function integer transform(){string str = getFieldName($in.0, -5); return 0;}","test_dynamiclib_getFieldName_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = getFieldName($in.0, 15); return 0;}","test_dynamiclib_getFieldName_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string str = fi.getFieldName(2); return 0;}","test_dynamiclib_getFieldName_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getFieldType(){ doCompile("test_dynamiclib_getFieldType"); check("ret1", "string"); check("ret2", "number"); } public void test_dynamiclib_getFieldType_expect_error(){ try { doCompile("function integer transform(){string str = getFieldType($in.0, -5); return 0;}","test_dynamiclib_getFieldType_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = getFieldType($in.0, 12); return 0;}","test_dynamiclib_getFieldType_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string str = fi.getFieldType(5); return 0;}","test_dynamiclib_getFieldType_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getIntValue(){ doCompile("test_dynamiclib_getIntValue"); check("ret1", CompilerTestCase.VALUE_VALUE); check("ret2", CompilerTestCase.VALUE_VALUE); check("ret3", CompilerTestCase.VALUE_VALUE); check("ret4", CompilerTestCase.VALUE_VALUE); check("ret5", null); } public void test_dynamiclib_getIntValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; integer i = fi.getIntValue(5); return 0;}","test_dynamiclib_getIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = getIntValue($in.0, 1); return 0;}","test_dynamiclib_getIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = getIntValue($in.0, 'Born'); return 0;}","test_dynamiclib_getIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getLongValue(){ doCompile("test_dynamiclib_getLongValue"); check("ret1", CompilerTestCase.BORN_MILLISEC_VALUE); check("ret2", CompilerTestCase.BORN_MILLISEC_VALUE); check("ret3", null); } public void test_dynamiclib_getLongValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; long l = getLongValue(fi, 4);return 0;} ","test_dynamiclib_getLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long l = getLongValue($in.0, 7);return 0;} ","test_dynamiclib_getLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long l = getLongValue($in.0, 'Age');return 0;} ","test_dynamiclib_getLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getNumValue(){ doCompile("test_dynamiclib_getNumValue"); check("ret1", CompilerTestCase.AGE_VALUE); check("ret2", CompilerTestCase.AGE_VALUE); check("ret3", null); } public void test_dynamiclib_getNumValue_expectValue(){ try { doCompile("function integer transform(){firstInput fi = null; number n = getNumValue(fi, 1); return 0;}","test_dynamiclib_getNumValue_expectValue"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number n = getNumValue($in.0, 4); return 0;}","test_dynamiclib_getNumValue_expectValue"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number n = $in.0.getNumValue('Name'); return 0;}","test_dynamiclib_getNumValue_expectValue"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getStringValue(){ doCompile("test_dynamiclib_getStringValue"); check("ret1", CompilerTestCase.NAME_VALUE); check("ret2", CompilerTestCase.NAME_VALUE); check("ret3", null); } public void test_dynamiclib_getStringValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; string str = getStringValue(fi, 0); return 0;}","test_dynamiclib_getStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = getStringValue($in.0, 5); return 0;}","test_dynamiclib_getStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = $in.0.getStringValue('Age'); return 0;}","test_dynamiclib_getStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getValueAsString(){ doCompile("test_dynamiclib_getValueAsString"); check("ret1", " HELLO "); check("ret2", "20.25"); check("ret3", "Chong'La"); check("ret4", "Sun Jan 25 13:25:55 CET 2009"); check("ret5", "1232886355333"); check("ret6", "2147483637"); check("ret7", "true"); check("ret8", "41626563656461207a65646c612064656461"); check("ret9", "133.525"); check("ret10", null); } public void test_dynamiclib_getValueAsString_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; string str = getValueAsString(fi, 1); return 0;}","test_dynamiclib_getValueAsString_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = getValueAsString($in.0, -1); return 0;}","test_dynamiclib_getValueAsString_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = $in.0.getValueAsString(10); return 0;}","test_dynamiclib_getValueAsString_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_isNull(){ doCompile("test_dynamiclib_isNull"); check("ret1", false); check("ret2", false); check("ret3", true); } public void test_dynamiclib_isNull_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; boolean b = fi.isNull(1); return 0;}","test_dynamiclib_isNull_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){boolean b = $in.0.isNull(-5); return 0;}","test_dynamiclib_isNull_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){boolean b = isNull($in.0,12); return 0;}","test_dynamiclib_isNull_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setBoolValue(){ doCompile("test_dynamiclib_setBoolValue"); check("ret1", null); check("ret2", true); check("ret3", false); } public void test_dynamiclib_setBoolValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setBoolValue(fi,6,true); return 0;}","test_dynamiclib_setBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setBoolValue($out.0,1,true); return 0;}","test_dynamiclib_setBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setBoolValue(15,true); return 0;}","test_dynamiclib_setBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setBoolValue(-1,true); return 0;}","test_dynamiclib_setBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setByteValue() throws UnsupportedEncodingException{ doCompile("test_dynamiclib_setByteValue"); checkArray("ret1", "Urgot".getBytes("UTF-8")); check("ret2", null); } public void test_dynamiclib_setByteValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi =null; setByteValue(fi,7,str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setByteValue($out.0, 1, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setByteValue($out.0, 12, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setByteValue(-2, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setDateValue(){ doCompile("test_dynamiclib_setDateValue"); Calendar cal = Calendar.getInstance(); cal.set(2006,10,12,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret1", cal.getTime()); check("ret2", null); } public void test_dynamiclib_setDateValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setDateValue(fi,'Born', null);return 0;}","test_dynamiclib_setDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setDateValue($out.0,1, null);return 0;}","test_dynamiclib_setDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setDateValue($out.0,-2, null);return 0;}","test_dynamiclib_setDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setDateValue(12, null);return 0;}","test_dynamiclib_setDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setDecimalValue(){ doCompile("test_dynamiclib_setDecimalValue"); check("ret1", new BigDecimal("12.300")); check("ret2", null); } public void test_dynamiclib_setDecimalValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setDecimalValue(fi, 'Currency', 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setDecimalValue($out.0, 'Name', 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setDecimalValue(-1, 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setDecimalValue(15, 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setIntValue(){ doCompile("test_dynamiclib_setIntValue"); check("ret1", 90); check("ret2", null); } public void test_dynamiclib_setIntValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi =null; setIntValue(fi,5,null);return 0;}","test_dynamiclib_setIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setIntValue($out.0,4,90);return 0;}","test_dynamiclib_setIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setIntValue($out.0,-2,90);return 0;}","test_dynamiclib_setIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setIntValue(15,90);return 0;}","test_dynamiclib_setIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setLongValue(){ doCompile("test_dynamiclib_setLongValue"); check("ret1", 1565486L); check("ret2", null); } public void test_dynamiclib_setLongValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setLongValue(fi, 4, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setLongValue($out.0, 0, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setLongValue($out.0, -1, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setLongValue(12, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setNumValue(){ doCompile("test_dynamiclib_setNumValue"); check("ret1", 12.5d); check("ret2", null); } public void test_dynamiclib_setNumValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setNumValue(fi, 'Age', 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setNumValue($out.0, 'Name', 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setNumValue($out.0, -1, 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setNumValue(11, 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setStringValue(){ doCompile("test_dynamiclib_setStringValue"); check("ret1", "Zac"); check("ret2", null); } public void test_dynamiclib_setStringValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setStringValue(fi, 'Name', 'Draven'); return 0;}","test_dynamiclib_setStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setStringValue($out.0, 'Age', 'Soraka'); return 0;}","test_dynamiclib_setStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setStringValue($out.0, -1, 'Rengar'); return 0;}","test_dynamiclib_setStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setStringValue(11, 'Vaigar'); return 0;}","test_dynamiclib_setStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_return_constants() { // test case for issue 2257 System.out.println("Return constants test:"); doCompile("test_return_constants"); check("skip", RecordTransform.SKIP); check("all", RecordTransform.ALL); check("ok", NORMALIZE_RETURN_OK); check("stop", RecordTransform.STOP); } public void test_ambiguous() { // built-in toString function doCompileExpectError("test_ambiguous_toString", "Function 'toString' is ambiguous"); // built-in join function doCompileExpectError("test_ambiguous_join", "Function 'join' is ambiguous"); // locally defined functions doCompileExpectError("test_ambiguous_localFunctions", "Function 'local' is ambiguous"); // locally overloaded built-in getUrlPath() function doCompileExpectError("test_ambiguous_combined", "Function 'getUrlPath' is ambiguous"); // swapped arguments - non null ambiguity doCompileExpectError("test_ambiguous_swapped", "Function 'swapped' is ambiguous"); // primitive type widening; the test depends on specific values of the type distance function, can be removed doCompileExpectError("test_ambiguous_widening", "Function 'widening' is ambiguous"); } public void test_raise_error_terminal() { // test case for issue 2337 doCompile("test_raise_error_terminal"); } public void test_raise_error_nonliteral() { // test case for issue CL-2071 doCompile("test_raise_error_nonliteral"); } public void test_case_unique_check() { // test case for issue 2515 doCompileExpectErrors("test_case_unique_check", Arrays.asList("Duplicate case", "Duplicate case")); } public void test_case_unique_check2() { // test case for issue 2515 doCompileExpectErrors("test_case_unique_check2", Arrays.asList("Duplicate case", "Duplicate case")); } public void test_case_unique_check3() { doCompileExpectError("test_case_unique_check3", "Default case is already defined"); } public void test_rvalue_for_append() { // test case for issue 3956 doCompile("test_rvalue_for_append"); check("a", Arrays.asList("1", "2")); check("b", Arrays.asList("a", "b", "c")); check("c", Arrays.asList("1", "2", "a", "b", "c")); } public void test_rvalue_for_map_append() { // test case for issue 3960 doCompile("test_rvalue_for_map_append"); HashMap<Integer, String> map1instance = new HashMap<Integer, String>(); map1instance.put(1, "a"); map1instance.put(2, "b"); HashMap<Integer, String> map2instance = new HashMap<Integer, String>(); map2instance.put(3, "c"); map2instance.put(4, "d"); HashMap<Integer, String> map3instance = new HashMap<Integer, String>(); map3instance.put(1, "a"); map3instance.put(2, "b"); map3instance.put(3, "c"); map3instance.put(4, "d"); check("map1", map1instance); check("map2", map2instance); check("map3", map3instance); } public void test_global_field_access() { // test case for issue 3957 doCompileExpectError("test_global_field_access", "Unable to access record field in global scope"); } public void test_global_scope() { // test case for issue 5006 doCompile("test_global_scope"); check("len", "Kokon".length()); } //TODO Implement /*public void test_new() { doCompile("test_new"); }*/ public void test_parser() { System.out.println("\nParser test:"); doCompile("test_parser"); } public void test_ref_res_import() { System.out.println("\nSpecial character resolving (import) test:"); URL importLoc = getClass().getSuperclass().getResource("test_ref_res.ctl"); String expStr = "import '" + importLoc + "';\n"; doCompile(expStr, "test_ref_res_import"); } public void test_ref_res_noimport() { System.out.println("\nSpecial character resolving (no import) test:"); doCompile("test_ref_res"); } public void test_import() { System.out.println("\nImport test:"); URL importLoc = getClass().getSuperclass().getResource("import.ctl"); String expStr = "import '" + importLoc + "';\n"; importLoc = getClass().getSuperclass().getResource("other.ctl"); expStr += "import '" + importLoc + "';\n" + "integer sumInt;\n" + "function integer transform() {\n" + " if (a == 3) {\n" + " otherImportVar++;\n" + " }\n" + " sumInt = sum(a, otherImportVar);\n" + " return 0;\n" + "}\n"; doCompile(expStr, "test_import"); } public void test_scope() throws ComponentNotReadyException, TransformException { System.out.println("\nMapping test:"); // String expStr = // "function string computeSomething(int n) {\n" + // " string s = '';\n" + // " do {\n" + // " int i = n--;\n" + // " s = s + '-' + i;\n" + // " } while (n > 0)\n" + // " return s;" + // "}\n\n" + // "function int transform() {\n" + // " printErr(computeSomething(10));\n" + // " return 0;\n" + // "}"; URL importLoc = getClass().getSuperclass().getResource("samplecode.ctl"); String expStr = "import '" + importLoc + "';\n"; // "function int getIndexOfOffsetStart(string encodedDate) {\n" + // "int offsetStart;\n" + // "int actualLastMinus;\n" + // "int lastMinus = -1;\n" + // "if ( index_of(encodedDate, '+') != -1 )\n" + // " return index_of(encodedDate, '+');\n" + // "do {\n" + // " actualLastMinus = index_of(encodedDate, '-', lastMinus+1);\n" + // " if ( actualLastMinus != -1 )\n" + // " lastMinus = actualLastMinus;\n" + // "} while ( actualLastMinus != -1 )\n" + // "return lastMinus;\n" + // "}\n" + // "function int transform() {\n" + // " getIndexOfOffsetStart('2009-04-24T08:00:00-05:00');\n" + // " return 0;\n" + // "}\n"; doCompile(expStr, "test_scope"); } //-------------------------- Data Types Tests --------------------- public void test_type_void() { doCompileExpectErrors("test_type_void", Arrays.asList("Syntax error on token 'void'", "Variable 'voidVar' is not declared", "Variable 'voidVar' is not declared", "Syntax error on token 'void'")); } public void test_type_integer() { doCompile("test_type_integer"); check("i", 0); check("j", -1); check("field", VALUE_VALUE); checkNull("nullValue"); check("varWithInitializer", 123); checkNull("varWithNullInitializer"); } public void test_type_integer_edge() { String testExpression = "integer minInt;\n"+ "integer maxInt;\n"+ "function integer transform() {\n" + "minInt=" + Integer.MIN_VALUE + ";\n" + "printErr(minInt, true);\n" + "maxInt=" + Integer.MAX_VALUE + ";\n" + "printErr(maxInt, true);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_int_edge"); check("minInt", Integer.MIN_VALUE); check("maxInt", Integer.MAX_VALUE); } public void test_type_long() { doCompile("test_type_long"); check("i", Long.valueOf(0)); check("j", Long.valueOf(-1)); check("field", BORN_MILLISEC_VALUE); check("def", Long.valueOf(0)); checkNull("nullValue"); check("varWithInitializer", 123L); checkNull("varWithNullInitializer"); } public void test_type_long_edge() { String expStr = "long minLong;\n"+ "long maxLong;\n"+ "function integer transform() {\n" + "minLong=" + (Long.MIN_VALUE) + "L;\n" + "printErr(minLong);\n" + "maxLong=" + (Long.MAX_VALUE) + "L;\n" + "printErr(maxLong);\n" + "return 0;\n" + "}\n"; doCompile(expStr,"test_long_edge"); check("minLong", Long.MIN_VALUE); check("maxLong", Long.MAX_VALUE); } public void test_type_decimal() { doCompile("test_type_decimal"); check("i", new BigDecimal(0, MAX_PRECISION)); check("j", new BigDecimal(-1, MAX_PRECISION)); check("field", CURRENCY_VALUE); check("def", new BigDecimal(0, MAX_PRECISION)); checkNull("nullValue"); check("varWithInitializer", new BigDecimal("123.35", MAX_PRECISION)); checkNull("varWithNullInitializer"); check("varWithInitializerNoDist", new BigDecimal(123.35, MAX_PRECISION)); } public void test_type_decimal_edge() { String testExpression = "decimal minLong;\n"+ "decimal maxLong;\n"+ "decimal minLongNoDist;\n"+ "decimal maxLongNoDist;\n"+ "decimal minDouble;\n"+ "decimal maxDouble;\n"+ "decimal minDoubleNoDist;\n"+ "decimal maxDoubleNoDist;\n"+ "function integer transform() {\n" + "minLong=" + String.valueOf(Long.MIN_VALUE) + "d;\n" + "printErr(minLong);\n" + "maxLong=" + String.valueOf(Long.MAX_VALUE) + "d;\n" + "printErr(maxLong);\n" + "minLongNoDist=" + String.valueOf(Long.MIN_VALUE) + "L;\n" + "printErr(minLongNoDist);\n" + "maxLongNoDist=" + String.valueOf(Long.MAX_VALUE) + "L;\n" + "printErr(maxLongNoDist);\n" + // distincter will cause the double-string be parsed into exact representation within BigDecimal "minDouble=" + String.valueOf(Double.MIN_VALUE) + "D;\n" + "printErr(minDouble);\n" + "maxDouble=" + String.valueOf(Double.MAX_VALUE) + "D;\n" + "printErr(maxDouble);\n" + // no distincter will cause the double-string to be parsed into inexact representation within double // then to be assigned into BigDecimal (which will extract only MAX_PRECISION digits) "minDoubleNoDist=" + String.valueOf(Double.MIN_VALUE) + ";\n" + "printErr(minDoubleNoDist);\n" + "maxDoubleNoDist=" + String.valueOf(Double.MAX_VALUE) + ";\n" + "printErr(maxDoubleNoDist);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_decimal_edge"); check("minLong", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION)); check("maxLong", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION)); check("minLongNoDist", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION)); check("maxLongNoDist", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION)); // distincter will cause the MIN_VALUE to be parsed into exact representation (i.e. 4.9E-324) check("minDouble", new BigDecimal(String.valueOf(Double.MIN_VALUE), MAX_PRECISION)); check("maxDouble", new BigDecimal(String.valueOf(Double.MAX_VALUE), MAX_PRECISION)); // no distincter will cause MIN_VALUE to be parsed into double inexact representation and extraction of // MAX_PRECISION digits (i.e. 4.94065.....E-324) check("minDoubleNoDist", new BigDecimal(Double.MIN_VALUE, MAX_PRECISION)); check("maxDoubleNoDist", new BigDecimal(Double.MAX_VALUE, MAX_PRECISION)); } public void test_type_number() { doCompile("test_type_number"); check("i", Double.valueOf(0)); check("j", Double.valueOf(-1)); check("field", AGE_VALUE); check("def", Double.valueOf(0)); checkNull("nullValue"); checkNull("varWithNullInitializer"); } public void test_type_number_edge() { String testExpression = "number minDouble;\n" + "number maxDouble;\n"+ "function integer transform() {\n" + "minDouble=" + Double.MIN_VALUE + ";\n" + "printErr(minDouble);\n" + "maxDouble=" + Double.MAX_VALUE + ";\n" + "printErr(maxDouble);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_number_edge"); check("minDouble", Double.valueOf(Double.MIN_VALUE)); check("maxDouble", Double.valueOf(Double.MAX_VALUE)); } public void test_type_string() { doCompile("test_type_string"); check("i","0"); check("helloEscaped", "hello\\nworld"); check("helloExpanded", "hello\nworld"); check("fieldName", NAME_VALUE); check("fieldCity", CITY_VALUE); check("escapeChars", "a\u0101\u0102A"); check("doubleEscapeChars", "a\\u0101\\u0102A"); check("specialChars", "špeciálne značky s mäkčeňom môžu byť"); check("dQescapeChars", "a\u0101\u0102A"); //TODO:Is next test correct? check("dQdoubleEscapeChars", "a\\u0101\\u0102A"); check("dQspecialChars", "špeciálne značky s mäkčeňom môžu byť"); check("empty", ""); check("def", ""); checkNull("varWithNullInitializer"); } public void test_type_string_long() { int length = 1000; StringBuilder tmp = new StringBuilder(length); for (int i = 0; i < length; i++) { tmp.append(i % 10); } String testExpression = "string longString;\n" + "function integer transform() {\n" + "longString=\"" + tmp + "\";\n" + "printErr(longString);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_string_long"); check("longString", String.valueOf(tmp)); } public void test_type_date() throws Exception { doCompile("test_type_date"); check("d3", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 1).getTime()); check("d2", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3).getTime()); check("d1", new GregorianCalendar(2006, GregorianCalendar.JANUARY, 1, 1, 2, 3).getTime()); check("field", BORN_VALUE); checkNull("nullValue"); check("minValue", new GregorianCalendar(1970, GregorianCalendar.JANUARY, 1, 1, 0, 0).getTime()); checkNull("varWithNullInitializer"); // test with a default time zone set on the GraphRuntimeContext Context context = null; try { tearDown(); setUp(); TransformationGraph graph = new TransformationGraph(); graph.getRuntimeContext().setTimeZone("GMT+8"); context = ContextProvider.registerGraph(graph); doCompile("test_type_date"); Calendar calendar = new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3); calendar.setTimeZone(TimeZone.getTimeZone("GMT+8")); check("d2", calendar.getTime()); calendar.set(2006, 0, 1, 1, 2, 3); check("d1", calendar.getTime()); } finally { ContextProvider.unregister(context); } } public void test_type_boolean() { doCompile("test_type_boolean"); check("b1", true); check("b2", false); check("b3", false); checkNull("nullValue"); checkNull("varWithNullInitializer"); } public void test_type_boolean_compare() { doCompileExpectErrors("test_type_boolean_compare", Arrays.asList( "Operator '>' is not defined for types 'boolean' and 'boolean'", "Operator '>=' is not defined for types 'boolean' and 'boolean'", "Operator '<' is not defined for types 'boolean' and 'boolean'", "Operator '<=' is not defined for types 'boolean' and 'boolean'", "Operator '<' is not defined for types 'boolean' and 'boolean'", "Operator '>' is not defined for types 'boolean' and 'boolean'", "Operator '>=' is not defined for types 'boolean' and 'boolean'", "Operator '<=' is not defined for types 'boolean' and 'boolean'")); } public void test_type_list() { doCompile("test_type_list"); check("intList", Arrays.asList(1, 2, 3, 4, 5, 6)); check("intList2", Arrays.asList(1, 2, 3)); check("stringList", Arrays.asList( "first", "replaced", "third", "fourth", "fifth", "sixth", "extra")); check("stringListCopy", Arrays.asList( "first", "second", "third", "fourth", "fifth", "seventh")); check("stringListCopy2", Arrays.asList( "first", "replaced", "third", "fourth", "fifth", "sixth", "extra")); assertTrue(getVariable("stringList") != getVariable("stringListCopy")); assertEquals(getVariable("stringList"), getVariable("stringListCopy2")); assertEquals(Arrays.asList(false, null, true), getVariable("booleanList")); assertDeepEquals(Arrays.asList(new byte[] {(byte) 0xAB}, null), getVariable("byteList")); assertDeepEquals(Arrays.asList(null, new byte[] {(byte) 0xCD}), getVariable("cbyteList")); assertEquals(Arrays.asList(new Date(12000), null, new Date(34000)), getVariable("dateList")); assertEquals(Arrays.asList(null, new BigDecimal(BigInteger.valueOf(1234), 2)), getVariable("decimalList")); assertEquals(Arrays.asList(12, null, 34), getVariable("intList3")); assertEquals(Arrays.asList(12l, null, 98l), getVariable("longList")); assertEquals(Arrays.asList(12.34, null, 56.78), getVariable("numberList")); assertEquals(Arrays.asList("aa", null, "bb"), getVariable("stringList2")); List<?> decimalList2 = (List<?>) getVariable("decimalList2"); for (Object o: decimalList2) { assertTrue(o instanceof BigDecimal); } List<?> intList4 = (List<?>) getVariable("intList4"); Set<Object> intList4Set = new HashSet<Object>(intList4); assertEquals(3, intList4Set.size()); } public void test_type_list_field() { doCompile("test_type_list_field"); check("copyByValueTest1", "2"); check("copyByValueTest2", "test"); } public void test_type_map_field() { doCompile("test_type_map_field"); Integer copyByValueTest1 = (Integer) getVariable("copyByValueTest1"); assertEquals(new Integer(2), copyByValueTest1); Integer copyByValueTest2 = (Integer) getVariable("copyByValueTest2"); assertEquals(new Integer(100), copyByValueTest2); } /** * The structure of the objects must be exactly the same! * * @param o1 * @param o2 */ private static void assertDeepCopy(Object o1, Object o2) { if (o1 instanceof DataRecord) { assertFalse(o1 == o2); DataRecord r1 = (DataRecord) o1; DataRecord r2 = (DataRecord) o2; for (int i = 0; i < r1.getNumFields(); i++) { assertDeepCopy(r1.getField(i).getValue(), r2.getField(i).getValue()); } } else if (o1 instanceof Map) { assertFalse(o1 == o2); Map<?, ?> m1 = (Map<?, ?>) o1; Map<?, ?> m2 = (Map<?, ?>) o2; for (Object key: m1.keySet()) { assertDeepCopy(m1.get(key), m2.get(key)); } } else if (o1 instanceof List) { assertFalse(o1 == o2); List<?> l1 = (List<?>) o1; List<?> l2 = (List<?>) o2; for (int i = 0; i < l1.size(); i++) { assertDeepCopy(l1.get(i), l2.get(i)); } } else if (o1 instanceof Date) { assertFalse(o1 == o2); // } else if (o1 instanceof byte[]) { // not required anymore // assertFalse(o1 == o2); } } /** * The structure of the objects must be exactly the same! * * @param o1 * @param o2 */ private static void assertDeepEquals(Object o1, Object o2) { if ((o1 == null) && (o2 == null)) { return; } assertTrue((o1 == null) == (o2 == null)); if (o1 instanceof DataRecord) { DataRecord r1 = (DataRecord) o1; DataRecord r2 = (DataRecord) o2; assertEquals(r1.getNumFields(), r2.getNumFields()); for (int i = 0; i < r1.getNumFields(); i++) { assertDeepEquals(r1.getField(i).getValue(), r2.getField(i).getValue()); } } else if (o1 instanceof Map) { Map<?, ?> m1 = (Map<?, ?>) o1; Map<?, ?> m2 = (Map<?, ?>) o2; assertTrue(m1.keySet().equals(m2.keySet())); for (Object key: m1.keySet()) { assertDeepEquals(m1.get(key), m2.get(key)); } } else if (o1 instanceof List) { List<?> l1 = (List<?>) o1; List<?> l2 = (List<?>) o2; assertEquals("size", l1.size(), l2.size()); for (int i = 0; i < l1.size(); i++) { assertDeepEquals(l1.get(i), l2.get(i)); } } else if (o1 instanceof byte[]) { byte[] b1 = (byte[]) o1; byte[] b2 = (byte[]) o2; if (b1 != b2) { if (b1 == null || b2 == null) { assertEquals(b1, b2); } assertEquals("length", b1.length, b2.length); for (int i = 0; i < b1.length; i++) { assertEquals(String.format("[%d]", i), b1[i], b2[i]); } } } else if (o1 instanceof CharSequence) { String s1 = ((CharSequence) o1).toString(); String s2 = ((CharSequence) o2).toString(); assertEquals(s1, s2); } else if ((o1 instanceof Decimal) || (o1 instanceof BigDecimal)) { BigDecimal d1 = o1 instanceof Decimal ? ((Decimal) o1).getBigDecimalOutput() : (BigDecimal) o1; BigDecimal d2 = o2 instanceof Decimal ? ((Decimal) o2).getBigDecimalOutput() : (BigDecimal) o2; assertEquals(d1, d2); } else { assertEquals(o1, o2); } } private void check_assignment_deepcopy_variable_declaration() { Date testVariableDeclarationDate1 = (Date) getVariable("testVariableDeclarationDate1"); Date testVariableDeclarationDate2 = (Date) getVariable("testVariableDeclarationDate2"); byte[] testVariableDeclarationByte1 = (byte[]) getVariable("testVariableDeclarationByte1"); byte[] testVariableDeclarationByte2 = (byte[]) getVariable("testVariableDeclarationByte2"); assertDeepEquals(testVariableDeclarationDate1, testVariableDeclarationDate2); assertDeepEquals(testVariableDeclarationByte1, testVariableDeclarationByte2); assertDeepCopy(testVariableDeclarationDate1, testVariableDeclarationDate2); assertDeepCopy(testVariableDeclarationByte1, testVariableDeclarationByte2); } @SuppressWarnings("unchecked") private void check_assignment_deepcopy_array_access_expression() { { // JJTARRAYACCESSEXPRESSION - List List<String> stringListField1 = (List<String>) getVariable("stringListField1"); DataRecord recordInList1 = (DataRecord) getVariable("recordInList1"); List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1"); List<DataRecord> recordList2 = (List<DataRecord>) getVariable("recordList2"); assertDeepEquals(stringListField1, recordInList1.getField("stringListField").getValue()); assertDeepEquals(recordInList1, recordList1.get(0)); assertDeepEquals(recordList1, recordList2); assertDeepCopy(stringListField1, recordInList1.getField("stringListField").getValue()); assertDeepCopy(recordInList1, recordList1.get(0)); assertDeepCopy(recordList1, recordList2); } { // map of records Date testDate1 = (Date) getVariable("testDate1"); Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1"); DataRecord recordInMap1 = (DataRecord) getVariable("recordInMap1"); DataRecord recordInMap2 = (DataRecord) getVariable("recordInMap2"); Map<Integer, DataRecord> recordMap2 = (Map<Integer, DataRecord>) getVariable("recordMap2"); assertDeepEquals(testDate1, recordInMap1.getField("dateField").getValue()); assertDeepEquals(recordInMap1, recordMap1.get(0)); assertDeepEquals(recordInMap2, recordMap1.get(0)); assertDeepEquals(recordMap1, recordMap2); assertDeepCopy(testDate1, recordInMap1.getField("dateField").getValue()); assertDeepCopy(recordInMap1, recordMap1.get(0)); assertDeepCopy(recordInMap2, recordMap1.get(0)); assertDeepCopy(recordMap1, recordMap2); } { // map of dates Map<Integer, Date> dateMap1 = (Map<Integer, Date>) getVariable("dateMap1"); Date date1 = (Date) getVariable("date1"); Date date2 = (Date) getVariable("date2"); assertDeepCopy(date1, dateMap1.get(0)); assertDeepCopy(date2, dateMap1.get(1)); } { // map of byte arrays Map<Integer, byte[]> byteMap1 = (Map<Integer, byte[]>) getVariable("byteMap1"); byte[] byte1 = (byte[]) getVariable("byte1"); byte[] byte2 = (byte[]) getVariable("byte2"); assertDeepCopy(byte1, byteMap1.get(0)); assertDeepCopy(byte2, byteMap1.get(1)); } { // JJTARRAYACCESSEXPRESSION - Function call List<String> testArrayAccessFunctionCallStringList = (List<String>) getVariable("testArrayAccessFunctionCallStringList"); DataRecord testArrayAccessFunctionCall = (DataRecord) getVariable("testArrayAccessFunctionCall"); Map<String, DataRecord> function_call_original_map = (Map<String, DataRecord>) getVariable("function_call_original_map"); Map<String, DataRecord> function_call_copied_map = (Map<String, DataRecord>) getVariable("function_call_copied_map"); List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list"); List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list"); assertDeepEquals(testArrayAccessFunctionCallStringList, testArrayAccessFunctionCall.getField("stringListField").getValue()); assertEquals(1, function_call_original_map.size()); assertEquals(2, function_call_copied_map.size()); assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall), function_call_original_list); assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall, testArrayAccessFunctionCall), function_call_copied_list); assertDeepEquals(testArrayAccessFunctionCall, function_call_original_map.get("1")); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("1")); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("2")); assertDeepEquals(testArrayAccessFunctionCall, function_call_original_list.get(1)); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(1)); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(2)); assertDeepCopy(testArrayAccessFunctionCall, function_call_original_map.get("1")); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("1")); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("2")); assertDeepCopy(testArrayAccessFunctionCall, function_call_original_list.get(1)); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(1)); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(2)); } // CLO-1210 { check("stringListNull", Arrays.asList((Object) null)); Map<String, String> stringMapNull = new HashMap<String, String>(); stringMapNull.put("a", null); check("stringMapNull", stringMapNull); } } @SuppressWarnings("unchecked") private void check_assignment_deepcopy_field_access_expression() { // field access Date testFieldAccessDate1 = (Date) getVariable("testFieldAccessDate1"); String testFieldAccessString1 = (String) getVariable("testFieldAccessString1"); List<Date> testFieldAccessDateList1 = (List<Date>) getVariable("testFieldAccessDateList1"); List<String> testFieldAccessStringList1 = (List<String>) getVariable("testFieldAccessStringList1"); Map<String, Date> testFieldAccessDateMap1 = (Map<String, Date>) getVariable("testFieldAccessDateMap1"); Map<String, String> testFieldAccessStringMap1 = (Map<String, String>) getVariable("testFieldAccessStringMap1"); DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1"); DataRecord firstMultivalueOutput = outputRecords[4]; DataRecord secondMultivalueOutput = outputRecords[5]; DataRecord thirdMultivalueOutput = outputRecords[6]; assertDeepEquals(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue()); assertDeepEquals(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0)); assertDeepEquals(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0)); assertDeepEquals(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first")); assertDeepEquals(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first")); assertDeepEquals(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue()); assertDeepEquals(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue()); assertDeepEquals(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue()); assertDeepEquals(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue()); assertDeepEquals(testFieldAccessRecord1, thirdMultivalueOutput); assertDeepCopy(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue()); assertDeepCopy(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0)); assertDeepCopy(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0)); assertDeepCopy(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first")); assertDeepCopy(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first")); assertDeepCopy(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue()); assertDeepCopy(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue()); assertDeepCopy(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue()); assertDeepCopy(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue()); assertDeepCopy(testFieldAccessRecord1, thirdMultivalueOutput); } @SuppressWarnings("unchecked") private void check_assignment_deepcopy_member_access_expression() { { // member access - record Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1"); byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1"); List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1"); List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1"); DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1"); DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); } { // member access - record Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1"); byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1"); List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1"); List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1"); DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1"); DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2"); DataRecord testMemberAccessRecord3 = (DataRecord) getVariable("testMemberAccessRecord3"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); assertDeepEquals(testMemberAccessRecord3, testMemberAccessRecord2); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); assertDeepCopy(testMemberAccessRecord3, testMemberAccessRecord2); // dictionary Date dictionaryDate = (Date) graph.getDictionary().getEntry("a").getValue(); byte[] dictionaryByte = (byte[]) graph.getDictionary().getEntry("y").getValue(); List<String> testMemberAccessStringList1 = (List<String>) getVariable("testMemberAccessStringList1"); List<Date> testMemberAccessDateList2 = (List<Date>) getVariable("testMemberAccessDateList2"); List<byte[]> testMemberAccessByteList2 = (List<byte[]>) getVariable("testMemberAccessByteList2"); List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList"); List<Date> dictionaryDateList = (List<Date>) graph.getDictionary().getValue("dateList"); List<byte[]> dictionaryByteList = (List<byte[]>) graph.getDictionary().getValue("byteList"); assertDeepEquals(dictionaryDate, testMemberAccessDate1); assertDeepEquals(dictionaryByte, testMemberAccessByte1); assertDeepEquals(dictionaryStringList, testMemberAccessStringList1); assertDeepEquals(dictionaryDateList, testMemberAccessDateList2); assertDeepEquals(dictionaryByteList, testMemberAccessByteList2); assertDeepCopy(dictionaryDate, testMemberAccessDate1); assertDeepCopy(dictionaryByte, testMemberAccessByte1); assertDeepCopy(dictionaryStringList, testMemberAccessStringList1); assertDeepCopy(dictionaryDateList, testMemberAccessDateList2); assertDeepCopy(dictionaryByteList, testMemberAccessByteList2); // member access - array of records List<DataRecord> testMemberAccessRecordList1 = (List<DataRecord>) getVariable("testMemberAccessRecordList1"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue()); assertDeepEquals(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2)); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue()); assertDeepCopy(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2)); // member access - map of records Map<Integer, DataRecord> testMemberAccessRecordMap1 = (Map<Integer, DataRecord>) getVariable("testMemberAccessRecordMap1"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue()); assertDeepEquals(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2)); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue()); assertDeepCopy(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2)); } } @SuppressWarnings("unchecked") public void test_assignment_deepcopy() { doCompile("test_assignment_deepcopy"); List<DataRecord> secondRecordList = (List<DataRecord>) getVariable("secondRecordList"); assertEquals("before", secondRecordList.get(0).getField("Name").getValue().toString()); List<DataRecord> firstRecordList = (List<DataRecord>) getVariable("firstRecordList"); assertEquals("after", firstRecordList.get(0).getField("Name").getValue().toString()); check_assignment_deepcopy_variable_declaration(); check_assignment_deepcopy_array_access_expression(); check_assignment_deepcopy_field_access_expression(); check_assignment_deepcopy_member_access_expression(); } public void test_assignment_deepcopy_field_access_expression() { doCompile("test_assignment_deepcopy_field_access_expression"); DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1"); DataRecord firstMultivalueOutput = outputRecords[4]; DataRecord secondMultivalueOutput = outputRecords[5]; DataRecord thirdMultivalueOutput = outputRecords[6]; DataRecord multivalueInput = inputRecords[3]; assertDeepEquals(firstMultivalueOutput, testFieldAccessRecord1); assertDeepEquals(secondMultivalueOutput, multivalueInput); assertDeepEquals(thirdMultivalueOutput, secondMultivalueOutput); assertDeepCopy(firstMultivalueOutput, testFieldAccessRecord1); assertDeepCopy(secondMultivalueOutput, multivalueInput); assertDeepCopy(thirdMultivalueOutput, secondMultivalueOutput); } public void test_assignment_array_access_function_call() { doCompile("test_assignment_array_access_function_call"); Map<String, String> originalMap = new HashMap<String, String>(); originalMap.put("a", "b"); Map<String, String> copiedMap = new HashMap<String, String>(originalMap); copiedMap.put("c", "d"); check("originalMap", originalMap); check("copiedMap", copiedMap); } public void test_assignment_array_access_function_call_wrong_type() { doCompileExpectErrors("test_assignment_array_access_function_call_wrong_type", Arrays.asList( "Expression is not a composite type but is resolved to 'string'", "Type mismatch: cannot convert from 'integer' to 'string'", "Cannot convert from 'integer' to string" )); } @SuppressWarnings("unchecked") public void test_assignment_returnvalue() { doCompile("test_assignment_returnvalue"); { List<String> stringList1 = (List<String>) getVariable("stringList1"); List<String> stringList2 = (List<String>) getVariable("stringList2"); List<String> stringList3 = (List<String>) getVariable("stringList3"); List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1"); Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1"); List<String> stringList4 = (List<String>) getVariable("stringList4"); Map<String, Integer> integerMap1 = (Map<String, Integer>) getVariable("integerMap1"); DataRecord record1 = (DataRecord) getVariable("record1"); DataRecord record2 = (DataRecord) getVariable("record2"); DataRecord firstMultivalueOutput = outputRecords[4]; DataRecord secondMultivalueOutput = outputRecords[5]; DataRecord thirdMultivalueOutput = outputRecords[6]; Date dictionaryDate1 = (Date) getVariable("dictionaryDate1"); Date dictionaryDate = (Date) graph.getDictionary().getValue("a"); Date zeroDate = new Date(0); List<String> testReturnValueDictionary2 = (List<String>) getVariable("testReturnValueDictionary2"); List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList"); List<String> testReturnValue10 = (List<String>) getVariable("testReturnValue10"); DataRecord testReturnValue11 = (DataRecord) getVariable("testReturnValue11"); List<String> testReturnValue12 = (List<String>) getVariable("testReturnValue12"); List<String> testReturnValue13 = (List<String>) getVariable("testReturnValue13"); Map<Integer, DataRecord> function_call_original_map = (Map<Integer, DataRecord>) getVariable("function_call_original_map"); Map<Integer, DataRecord> function_call_copied_map = (Map<Integer, DataRecord>) getVariable("function_call_copied_map"); DataRecord function_call_map_newrecord = (DataRecord) getVariable("function_call_map_newrecord"); List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list"); List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list"); DataRecord function_call_list_newrecord = (DataRecord) getVariable("function_call_list_newrecord"); // identifier assertFalse(stringList1.isEmpty()); assertTrue(stringList2.isEmpty()); assertTrue(stringList3.isEmpty()); // array access expression - list assertDeepEquals("unmodified", recordList1.get(0).getField("stringField").getValue()); assertDeepEquals("modified", recordList1.get(1).getField("stringField").getValue()); // array access expression - map assertDeepEquals("unmodified", recordMap1.get(0).getField("stringField").getValue()); assertDeepEquals("modified", recordMap1.get(1).getField("stringField").getValue()); // array access expression - function call assertDeepEquals(null, function_call_original_map.get(2)); assertDeepEquals("unmodified", function_call_map_newrecord.getField("stringField")); assertDeepEquals("modified", function_call_copied_map.get(2).getField("stringField")); assertDeepEquals(Arrays.asList(null, function_call_list_newrecord), function_call_original_list); assertDeepEquals("unmodified", function_call_list_newrecord.getField("stringField")); assertDeepEquals("modified", function_call_copied_list.get(2).getField("stringField")); // field access expression assertFalse(stringList4.isEmpty()); assertTrue(((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).isEmpty()); assertFalse(integerMap1.isEmpty()); assertTrue(((Map<?, ?>) firstMultivalueOutput.getField("integerMapField").getValue()).isEmpty()); assertDeepEquals("unmodified", record1.getField("stringField")); assertDeepEquals("modified", secondMultivalueOutput.getField("stringField").getValue()); assertDeepEquals("unmodified", record2.getField("stringField")); assertDeepEquals("modified", thirdMultivalueOutput.getField("stringField").getValue()); // member access expression - dictionary // There is no function that could modify a date // assertEquals(zeroDate, dictionaryDate); // assertFalse(zeroDate.equals(testReturnValueDictionary1)); assertFalse(testReturnValueDictionary2.isEmpty()); assertTrue(dictionaryStringList.isEmpty()); // member access expression - record assertFalse(testReturnValue10.isEmpty()); assertTrue(((List<?>) testReturnValue11.getField("stringListField").getValue()).isEmpty()); // member access expression - list of records assertFalse(testReturnValue12.isEmpty()); assertTrue(((List<?>) recordList1.get(2).getField("stringListField").getValue()).isEmpty()); // member access expression - map of records assertFalse(testReturnValue13.isEmpty()); assertTrue(((List<?>) recordMap1.get(2).getField("stringListField").getValue()).isEmpty()); } } @SuppressWarnings("unchecked") public void test_type_map() { doCompile("test_type_map"); Map<String, Integer> testMap = (Map<String, Integer>) getVariable("testMap"); assertEquals(Integer.valueOf(1), testMap.get("zero")); assertEquals(Integer.valueOf(2), testMap.get("one")); assertEquals(Integer.valueOf(3), testMap.get("two")); assertEquals(Integer.valueOf(4), testMap.get("three")); assertEquals(4, testMap.size()); Map<Date, String> dayInWeek = (Map<Date, String>) getVariable("dayInWeek"); Calendar c = Calendar.getInstance(); c.set(2009, Calendar.MARCH, 2, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); assertEquals("Monday", dayInWeek.get(c.getTime())); Map<Date, String> dayInWeekCopy = (Map<Date, String>) getVariable("dayInWeekCopy"); c.set(2009, Calendar.MARCH, 3, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); assertEquals("Tuesday", ((Map<Date, String>) getVariable("tuesday")).get(c.getTime())); assertEquals("Tuesday", dayInWeekCopy.get(c.getTime())); c.set(2009, Calendar.MARCH, 4, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); assertEquals("Wednesday", ((Map<Date, String>) getVariable("wednesday")).get(c.getTime())); assertEquals("Wednesday", dayInWeekCopy.get(c.getTime())); assertFalse(dayInWeek.equals(dayInWeekCopy)); { Map<?, ?> preservedOrder = (Map<?, ?>) getVariable("preservedOrder"); assertEquals(100, preservedOrder.size()); int i = 0; for (Map.Entry<?, ?> entry: preservedOrder.entrySet()) { assertEquals("key" + i, entry.getKey()); assertEquals("value" + i, entry.getValue()); i++; } } } public void test_type_record_list() { doCompile("test_type_record_list"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record_list_global() { doCompile("test_type_record_list_global"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record_map() { doCompile("test_type_record_map"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record_map_global() { doCompile("test_type_record_map_global"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record() { doCompile("test_type_record"); // expected result DataRecord expected = createDefaultRecord(createDefaultMetadata("expected")); // simple copy assertTrue(recordEquals(expected, inputRecords[0])); assertTrue(recordEquals(expected, (DataRecord) getVariable("copy"))); // copy and modify expected.getField("Name").setValue("empty"); expected.getField("Value").setValue(321); Calendar c = Calendar.getInstance(); c.set(1987, Calendar.NOVEMBER, 13, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); expected.getField("Born").setValue(c.getTime()); assertTrue(recordEquals(expected, (DataRecord) getVariable("modified"))); // 2x modified copy expected.getField("Name").setValue("not empty"); assertTrue(recordEquals(expected, (DataRecord)getVariable("modified2"))); // no modification by reference is possible assertTrue(recordEquals(expected, (DataRecord)getVariable("modified3"))); expected.getField("Value").setValue(654321); assertTrue(recordEquals(expected, (DataRecord)getVariable("reference"))); assertTrue(getVariable("modified3") != getVariable("reference")); // output record assertTrue(recordEquals(expected, outputRecords[1])); // null record expected.setToNull(); assertTrue(recordEquals(expected, (DataRecord)getVariable("nullRecord"))); } //------------------------ Operator Tests --------------------------- public void test_variables() { doCompile("test_variables"); check("b1", true); check("b2", true); check("b4", "hi"); check("i", 2); } public void test_operator_plus() { doCompile("test_operator_plus"); check("iplusj", 10 + 100); check("lplusm", Long.valueOf(Integer.MAX_VALUE) + Long.valueOf(Integer.MAX_VALUE / 10)); check("mplusl", getVariable("lplusm")); check("mplusi", Long.valueOf(Integer.MAX_VALUE) + 10); check("iplusm", getVariable("mplusi")); check("nplusm1", Double.valueOf(0.1D + 0.001D)); check("nplusj", Double.valueOf(100 + 0.1D)); check("jplusn", getVariable("nplusj")); check("m1plusm", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) + 0.001d)); check("mplusm1", getVariable("m1plusm")); check("dplusd1", new BigDecimal("0.1", MAX_PRECISION).add(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dplusj", new BigDecimal(100, MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("jplusd", getVariable("dplusj")); check("dplusm", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("mplusd", getVariable("dplusm")); check("dplusn", new BigDecimal("0.1").add(new BigDecimal(0.1D, MAX_PRECISION))); check("nplusd", getVariable("dplusn")); check("spluss1", "hello world"); check("splusj", "hello100"); check("jpluss", "100hello"); check("splusm", "hello" + Long.valueOf(Integer.MAX_VALUE)); check("mpluss", Long.valueOf(Integer.MAX_VALUE) + "hello"); check("splusm1", "hello" + Double.valueOf(0.001D)); check("m1pluss", Double.valueOf(0.001D) + "hello"); check("splusd1", "hello" + new BigDecimal("0.0001")); check("d1pluss", new BigDecimal("0.0001", MAX_PRECISION) + "hello"); } public void test_operator_minus() { doCompile("test_operator_minus"); check("iminusj", 10 - 100); check("lminusm", Long.valueOf(Integer.MAX_VALUE / 10) - Long.valueOf(Integer.MAX_VALUE)); check("mminusi", Long.valueOf(Integer.MAX_VALUE - 10)); check("iminusm", 10 - Long.valueOf(Integer.MAX_VALUE)); check("nminusm1", Double.valueOf(0.1D - 0.001D)); check("nminusj", Double.valueOf(0.1D - 100)); check("jminusn", Double.valueOf(100 - 0.1D)); check("m1minusm", Double.valueOf(0.001D - Long.valueOf(Integer.MAX_VALUE))); check("mminusm1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) - 0.001D)); check("dminusd1", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dminusj", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION)); check("jminusd", new BigDecimal(100, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dminusm", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mminusd", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dminusn", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION)); check("nminusd", new BigDecimal(0.1D, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); } public void test_operator_multiply() { doCompile("test_operator_multiply"); check("itimesj", 10 * 100); check("ltimesm", Long.valueOf(Integer.MAX_VALUE) * (Long.valueOf(Integer.MAX_VALUE / 10))); check("mtimesl", getVariable("ltimesm")); check("mtimesi", Long.valueOf(Integer.MAX_VALUE) * 10); check("itimesm", getVariable("mtimesi")); check("ntimesm1", Double.valueOf(0.1D * 0.001D)); check("ntimesj", Double.valueOf(0.1) * 100); check("jtimesn", getVariable("ntimesj")); check("m1timesm", Double.valueOf(0.001d * Long.valueOf(Integer.MAX_VALUE))); check("mtimesm1", getVariable("m1timesm")); check("dtimesd1", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dtimesj", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(100, MAX_PRECISION))); check("jtimesd", getVariable("dtimesj")); check("dtimesm", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mtimesd", getVariable("dtimesm")); check("dtimesn", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(0.1, MAX_PRECISION), MAX_PRECISION)); check("ntimesd", getVariable("dtimesn")); } public void test_operator_divide() { doCompile("test_operator_divide"); check("idividej", 10 / 100); check("ldividem", Long.valueOf(Integer.MAX_VALUE / 10) / Long.valueOf(Integer.MAX_VALUE)); check("mdividei", Long.valueOf(Integer.MAX_VALUE / 10)); check("idividem", 10 / Long.valueOf(Integer.MAX_VALUE)); check("ndividem1", Double.valueOf(0.1D / 0.001D)); check("ndividej", Double.valueOf(0.1D / 100)); check("jdividen", Double.valueOf(100 / 0.1D)); check("m1dividem", Double.valueOf(0.001D / Long.valueOf(Integer.MAX_VALUE))); check("mdividem1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) / 0.001D)); check("ddivided1", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("ddividej", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION)); check("jdivided", new BigDecimal(100, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("ddividem", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mdivided", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("ddividen", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION)); check("ndivided", new BigDecimal(0.1D, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); } public void test_operator_modulus() { doCompile("test_operator_modulus"); check("imoduloj", 10 % 100); check("lmodulom", Long.valueOf(Integer.MAX_VALUE / 10) % Long.valueOf(Integer.MAX_VALUE)); check("mmoduloi", Long.valueOf(Integer.MAX_VALUE % 10)); check("imodulom", 10 % Long.valueOf(Integer.MAX_VALUE)); check("nmodulom1", Double.valueOf(0.1D % 0.001D)); check("nmoduloj", Double.valueOf(0.1D % 100)); check("jmodulon", Double.valueOf(100 % 0.1D)); check("m1modulom", Double.valueOf(0.001D % Long.valueOf(Integer.MAX_VALUE))); check("mmodulom1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) % 0.001D)); check("dmodulod1", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dmoduloj", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION)); check("jmodulod", new BigDecimal(100, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dmodulom", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mmodulod", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dmodulon", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION)); check("nmodulod", new BigDecimal(0.1D, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); } public void test_operators_unary() { doCompile("test_operators_unary"); // postfix operators // int check("intPlusOrig", Integer.valueOf(10)); check("intPlusPlus", Integer.valueOf(10)); check("intPlus", Integer.valueOf(11)); check("intMinusOrig", Integer.valueOf(10)); check("intMinusMinus", Integer.valueOf(10)); check("intMinus", Integer.valueOf(9)); // long check("longPlusOrig", Long.valueOf(10)); check("longPlusPlus", Long.valueOf(10)); check("longPlus", Long.valueOf(11)); check("longMinusOrig", Long.valueOf(10)); check("longMinusMinus", Long.valueOf(10)); check("longMinus", Long.valueOf(9)); // double check("numberPlusOrig", Double.valueOf(10.1)); check("numberPlusPlus", Double.valueOf(10.1)); check("numberPlus", Double.valueOf(11.1)); check("numberMinusOrig", Double.valueOf(10.1)); check("numberMinusMinus", Double.valueOf(10.1)); check("numberMinus", Double.valueOf(9.1)); // decimal check("decimalPlusOrig", new BigDecimal("10.1")); check("decimalPlusPlus", new BigDecimal("10.1")); check("decimalPlus", new BigDecimal("11.1")); check("decimalMinusOrig", new BigDecimal("10.1")); check("decimalMinusMinus", new BigDecimal("10.1")); check("decimalMinus", new BigDecimal("9.1")); // prefix operators // integer check("plusIntOrig", Integer.valueOf(10)); check("plusPlusInt", Integer.valueOf(11)); check("plusInt", Integer.valueOf(11)); check("minusIntOrig", Integer.valueOf(10)); check("minusMinusInt", Integer.valueOf(9)); check("minusInt", Integer.valueOf(9)); check("unaryInt", Integer.valueOf(-10)); // long check("plusLongOrig", Long.valueOf(10)); check("plusPlusLong", Long.valueOf(11)); check("plusLong", Long.valueOf(11)); check("minusLongOrig", Long.valueOf(10)); check("minusMinusLong", Long.valueOf(9)); check("minusLong", Long.valueOf(9)); check("unaryLong", Long.valueOf(-10)); // double check("plusNumberOrig", Double.valueOf(10.1)); check("plusPlusNumber", Double.valueOf(11.1)); check("plusNumber", Double.valueOf(11.1)); check("minusNumberOrig", Double.valueOf(10.1)); check("minusMinusNumber", Double.valueOf(9.1)); check("minusNumber", Double.valueOf(9.1)); check("unaryNumber", Double.valueOf(-10.1)); // decimal check("plusDecimalOrig", new BigDecimal("10.1")); check("plusPlusDecimal", new BigDecimal("11.1")); check("plusDecimal", new BigDecimal("11.1")); check("minusDecimalOrig", new BigDecimal("10.1")); check("minusMinusDecimal", new BigDecimal("9.1")); check("minusDecimal", new BigDecimal("9.1")); check("unaryDecimal", new BigDecimal("-10.1")); // record values assertEquals(101, ((DataRecord) getVariable("plusPlusRecord")).getField("Value").getValue()); assertEquals(101, ((DataRecord) getVariable("recordPlusPlus")).getField("Value").getValue()); assertEquals(101, ((DataRecord) getVariable("modifiedPlusPlusRecord")).getField("Value").getValue()); assertEquals(101, ((DataRecord) getVariable("modifiedRecordPlusPlus")).getField("Value").getValue()); //record as parameter assertEquals(99, ((DataRecord) getVariable("minusMinusRecord")).getField("Value").getValue()); assertEquals(99, ((DataRecord) getVariable("recordMinusMinus")).getField("Value").getValue()); assertEquals(99, ((DataRecord) getVariable("modifiedMinusMinusRecord")).getField("Value").getValue()); assertEquals(99, ((DataRecord) getVariable("modifiedRecordMinusMinus")).getField("Value").getValue()); // logical not check("booleanValue", true); check("negation", false); check("doubleNegation", true); } public void test_operators_unary_record() { doCompileExpectErrors("test_operators_unary_record", Arrays.asList( "Illegal argument to ++/-- operator", "Illegal argument to ++/-- operator", "Illegal argument to ++/-- operator", "Illegal argument to ++/-- operator", "Input record cannot be assigned to", "Input record cannot be assigned to", "Input record cannot be assigned to", "Input record cannot be assigned to" )); } public void test_operator_equal() { doCompile("test_operator_equal"); check("eq0", true); check("eq1", true); check("eq1a", true); check("eq1b", true); check("eq1c", false); check("eq2", true); check("eq3", true); check("eq4", true); check("eq5", true); check("eq6", false); check("eq7", true); check("eq8", false); check("eq9", true); check("eq10", false); check("eq11", true); check("eq12", false); check("eq13", true); check("eq14", false); check("eq15", false); check("eq16", true); check("eq17", false); check("eq18", false); check("eq19", false); // byte check("eq20", true); check("eq21", true); check("eq22", false); check("eq23", false); check("eq24", true); check("eq25", false); check("eq20c", true); check("eq21c", true); check("eq22c", false); check("eq23c", false); check("eq24c", true); check("eq25c", false); check("eq26", true); check("eq27", true); } public void test_operator_non_equal(){ doCompile("test_operator_non_equal"); check("inei", false); check("inej", true); check("jnei", true); check("jnej", false); check("lnei", false); check("inel", false); check("lnej", true); check("jnel", true); check("lnel", false); check("dnei", false); check("ined", false); check("dnej", true); check("jned", true); check("dnel", false); check("lned", false); check("dned", false); check("dned_different_scale", false); } public void test_operator_in() { doCompile("test_operator_in"); check("a", Integer.valueOf(1)); check("haystack", Collections.EMPTY_LIST); check("needle", Integer.valueOf(2)); check("b1", true); check("b2", false); check("h2", Arrays.asList(2.1D, 2.0D, 2.2D)); check("b3", true); check("h3", Arrays.asList("memento", "mori", "memento mori")); check("n3", "memento mori"); check("b4", true); check("ret1", false); check("ret2", true); check("ret3", false); check("ret4", true); check("ret5", false); check("ret6", true); check("ret7", false); check("ret8", true); check("ret9", false); check("ret10", true); check("ret11", false); check("ret12", true); check("ret13", false); check("ret14", true); check("ret15", false); check("ret16", true); check("ret17", false); check("ret18", false); check("ret19", true); check("ret20", false); check("ret21", false); } public void test_operator_in_expect_error(){ try { doCompile("function integer transform(){long[] lList = null; long l = 15l; boolean b = in(l, lList); return 0;}","test_operator_in_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[long, long] lMap = null; long l = 15l; boolean b = in(l, lMap); return 0;}","test_operator_in_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_operator_greater_less() { doCompile("test_operator_greater_less"); check("eq1", true); check("eq2", true); check("eq3", true); check("eq4", false); check("eq5", true); check("eq6", false); check("eq7", true); check("eq8", true); check("eq9", true); } public void test_operator_ternary(){ doCompile("test_operator_ternary"); // simple use check("trueValue", true); check("falseValue", false); check("res1", Integer.valueOf(1)); check("res2", Integer.valueOf(2)); // nesting in positive branch check("res3", Integer.valueOf(1)); check("res4", Integer.valueOf(2)); check("res5", Integer.valueOf(3)); // nesting in negative branch check("res6", Integer.valueOf(2)); check("res7", Integer.valueOf(3)); // nesting in both branches check("res8", Integer.valueOf(1)); check("res9", Integer.valueOf(1)); check("res10", Integer.valueOf(2)); check("res11", Integer.valueOf(3)); check("res12", Integer.valueOf(2)); check("res13", Integer.valueOf(4)); check("res14", Integer.valueOf(3)); check("res15", Integer.valueOf(4)); } public void test_operators_logical(){ doCompile("test_operators_logical"); //TODO: please double check this. check("res1", false); check("res2", false); check("res3", true); check("res4", true); check("res5", false); check("res6", false); check("res7", true); check("res8", false); } public void test_regex(){ doCompile("test_regex"); check("eq0", false); check("eq1", true); check("eq2", false); check("eq3", true); check("eq4", false); check("eq5", true); } public void test_if() { doCompile("test_if"); // if with single statement check("cond1", true); check("res1", true); // if with mutliple statements (block) check("cond2", true); check("res21", true); check("res22", true); // else with single statement check("cond3", false); check("res31", false); check("res32", true); // else with multiple statements (block) check("cond4", false); check("res41", false); check("res42", true); check("res43", true); // if with block, else with block check("cond5", false); check("res51", false); check("res52", false); check("res53", true); check("res54", true); // else-if with single statement check("cond61", false); check("cond62", true); check("res61", false); check("res62", true); // else-if with multiple statements check("cond71", false); check("cond72", true); check("res71", false); check("res72", true); check("res73", true); // if-elseif-else test check("cond81", false); check("cond82", false); check("res81", false); check("res82", false); check("res83", true); // if with single statement + inactive else check("cond9", true); check("res91", true); check("res92", false); // if with multiple statements + inactive else with block check("cond10", true); check("res101", true); check("res102", true); check("res103", false); check("res104", false); // if with condition check("i", 0); check("j", 1); check("res11", true); } public void test_switch() { doCompile("test_switch"); // simple switch check("cond1", 1); check("res11", false); check("res12", true); check("res13", false); // switch, no break check("cond2", 1); check("res21", false); check("res22", true); check("res23", true); // default branch check("cond3", 3); check("res31", false); check("res32", false); check("res33", true); // no default branch => no match check("cond4", 3); check("res41", false); check("res42", false); check("res43", false); // multiple statements in a single case-branch check("cond5", 1); check("res51", false); check("res52", true); check("res53", true); check("res54", false); // single statement shared by several case labels check("cond6", 1); check("res61", false); check("res62", true); check("res63", true); check("res64", false); check("res71", "default case"); check("res72", "null case"); check("res73", "null case"); check("res74", "default case"); } public void test_int_switch(){ doCompile("test_int_switch"); // simple switch check("cond1", 1); check("res11", true); check("res12", false); check("res13", false); // first case is not followed by a break check("cond2", 1); check("res21", true); check("res22", true); check("res23", false); // first and second case have multiple labels check("cond3", 12); check("res31", false); check("res32", true); check("res33", false); // first and second case have multiple labels and no break after first group check("cond4", 11); check("res41", true); check("res42", true); check("res43", false); // default case intermixed with other case labels in the second group check("cond5", 11); check("res51", true); check("res52", true); check("res53", true); // default case intermixed, with break check("cond6", 16); check("res61", false); check("res62", true); check("res63", false); // continue test check("res7", Arrays.asList( /* i=0 */false, false, false, /* i=1 */true, true, false, /* i=2 */true, true, false, /* i=3 */false, true, false, /* i=4 */false, true, false, /* i=5 */false, false, true)); // return test check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3")); } public void test_non_int_switch(){ doCompile("test_non_int_switch"); // simple switch check("cond1", "1"); check("res11", true); check("res12", false); check("res13", false); // first case is not followed by a break check("cond2", "1"); check("res21", true); check("res22", true); check("res23", false); // first and second case have multiple labels check("cond3", "12"); check("res31", false); check("res32", true); check("res33", false); // first and second case have multiple labels and no break after first group check("cond4", "11"); check("res41", true); check("res42", true); check("res43", false); // default case intermixed with other case labels in the second group check("cond5", "11"); check("res51", true); check("res52", true); check("res53", true); // default case intermixed, with break check("cond6", "16"); check("res61", false); check("res62", true); check("res63", false); // continue test check("res7", Arrays.asList( /* i=0 */false, false, false, /* i=1 */true, true, false, /* i=2 */true, true, false, /* i=3 */false, true, false, /* i=4 */false, true, false, /* i=5 */false, false, true)); // return test check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3")); } public void test_while() { doCompile("test_while"); // simple while check("res1", Arrays.asList(0, 1, 2)); // continue check("res2", Arrays.asList(0, 2)); // break check("res3", Arrays.asList(0)); } public void test_do_while() { doCompile("test_do_while"); // simple while check("res1", Arrays.asList(0, 1, 2)); // continue check("res2", Arrays.asList(0, null, 2)); // break check("res3", Arrays.asList(0)); } public void test_for() { doCompile("test_for"); // simple loop check("res1", Arrays.asList(0,1,2)); // continue check("res2", Arrays.asList(0,null,2)); // break check("res3", Arrays.asList(0)); // empty init check("res4", Arrays.asList(0,1,2)); // empty update check("res5", Arrays.asList(0,1,2)); // empty final condition check("res6", Arrays.asList(0,1,2)); // all conditions empty check("res7", Arrays.asList(0,1,2)); } public void test_for1() { //5125: CTL2: "for" cycle is EXTREMELY memory consuming doCompile("test_for1"); checkEquals("counter", "COUNT"); } @SuppressWarnings("unchecked") public void test_foreach() { doCompile("test_foreach"); check("intRes", Arrays.asList(VALUE_VALUE)); check("longRes", Arrays.asList(BORN_MILLISEC_VALUE)); check("doubleRes", Arrays.asList(AGE_VALUE)); check("decimalRes", Arrays.asList(CURRENCY_VALUE)); check("booleanRes", Arrays.asList(FLAG_VALUE)); check("stringRes", Arrays.asList(NAME_VALUE, CITY_VALUE)); check("dateRes", Arrays.asList(BORN_VALUE)); List<?> integerStringMapResTmp = (List<?>) getVariable("integerStringMapRes"); List<String> integerStringMapRes = new ArrayList<String>(integerStringMapResTmp.size()); for (Object o: integerStringMapResTmp) { integerStringMapRes.add(String.valueOf(o)); } List<Integer> stringIntegerMapRes = (List<Integer>) getVariable("stringIntegerMapRes"); List<DataRecord> stringRecordMapRes = (List<DataRecord>) getVariable("stringRecordMapRes"); Collections.sort(integerStringMapRes); Collections.sort(stringIntegerMapRes); assertEquals(Arrays.asList("0", "1", "2", "3", "4"), integerStringMapRes); assertEquals(Arrays.asList(0, 1, 2, 3, 4), stringIntegerMapRes); final int N = 5; assertEquals(N, stringRecordMapRes.size()); int equalRecords = 0; for (int i = 0; i < N; i++) { for (DataRecord r: stringRecordMapRes) { if (Integer.valueOf(i).equals(r.getField("Value").getValue()) && "A string".equals(String.valueOf(r.getField("Name").getValue()))) { equalRecords++; break; } } } assertEquals(N, equalRecords); } public void test_return(){ doCompile("test_return"); check("lhs", Integer.valueOf(1)); check("rhs", Integer.valueOf(2)); check("res", Integer.valueOf(3)); } public void test_return_incorrect() { doCompileExpectError("test_return_incorrect", "Can't convert from 'string' to 'integer'"); } public void test_return_void() { doCompile("test_return_void"); } public void test_overloading() { doCompile("test_overloading"); check("res1", Integer.valueOf(3)); check("res2", "Memento mori"); } public void test_overloading_incorrect() { doCompileExpectErrors("test_overloading_incorrect", Arrays.asList( "Duplicate function 'integer sum(integer, integer)'", "Duplicate function 'integer sum(integer, integer)'")); } //Test case for 4038 public void test_function_parameter_without_type() { doCompileExpectError("test_function_parameter_without_type", "Syntax error on token ')'"); } public void test_duplicate_import() { URL importLoc = getClass().getSuperclass().getResource("test_duplicate_import.ctl"); String expStr = "import '" + importLoc + "';\n"; expStr += "import '" + importLoc + "';\n"; doCompile(expStr, "test_duplicate_import"); } /*TODO: * public void test_invalid_import() { URL importLoc = getClass().getResource("test_duplicate_import.ctl"); String expStr = "import '/a/b/c/d/e/f/g/h/i/j/k/l/m';\n"; expStr += expStr; doCompileExpectError(expStr, "test_invalid_import", Arrays.asList("TODO: Unknown error")); //doCompileExpectError(expStr, "test_duplicate_import", Arrays.asList("TODO: Unknown error")); } */ public void test_built_in_functions(){ doCompile("test_built_in_functions"); check("notNullValue", Integer.valueOf(1)); checkNull("nullValue"); check("isNullRes1", false); check("isNullRes2", true); assertEquals("nvlRes1", getVariable("notNullValue"), getVariable("nvlRes1")); check("nvlRes2", Integer.valueOf(2)); assertEquals("nvl2Res1", getVariable("notNullValue"), getVariable("nvl2Res1")); check("nvl2Res2", Integer.valueOf(2)); check("iifRes1", Integer.valueOf(2)); check("iifRes2", Integer.valueOf(1)); } public void test_local_functions() { // CLO-1246 doCompile("test_local_functions"); } public void test_mapping(){ doCompile("test_mapping"); // simple mappings assertEquals("Name", NAME_VALUE, outputRecords[0].getField("Name").getValue().toString()); assertEquals("Age", AGE_VALUE, outputRecords[0].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[0].getField("City").getValue().toString()); assertEquals("Born", BORN_VALUE, outputRecords[0].getField("Born").getValue()); // * mapping assertTrue(recordEquals(inputRecords[1], outputRecords[1])); check("len", 2); } public void test_mapping_null_values() { doCompile("test_mapping_null_values"); assertTrue(recordEquals(inputRecords[2], outputRecords[0])); } public void test_copyByName() { doCompile("test_copyByName"); assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue()); assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString()); } public void test_copyByName_expect_error(){ try { doCompile("function integer transform(){\n" + "firstInput fi1 = null; firstInput fi2;\n" + "copyByName(fi1, fi2); \n" + "return 0;}","test_copyByName_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "firstInput fi1 = null; firstInput fi2 = null;\n" + "copyByName(fi1, fi2); \n" + "return 0;}","test_copyByName_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_copyByName_assignment() { doCompile("test_copyByName_assignment"); assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue()); assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString()); } public void test_copyByName_assignment1() { doCompile("test_copyByName_assignment1"); assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue()); assertEquals("Age", null, outputRecords[3].getField("Age").getValue()); assertEquals("City", null, outputRecords[3].getField("City").getValue()); } public void test_containerlib_copyByPosition(){ doCompile("test_containerlib_copyByPosition"); assertEquals("Field1", NAME_VALUE, outputRecords[3].getField("Field1").getValue().toString()); assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString()); } public void test_containerlib_copyByPosition_expect_error(){ try { doCompile("function integer transform(){\n" + "firstInput fi1 = null; firstInput fi2; \n" + "copyByPosition(fi1, fi2);\n" + "return 0;}","test_containerlib_copyByPosition_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "firstInput fi1 = null; firstInput fi2 = null; \n" + "copyByPosition(fi1, fi2);\n" + "return 0;}","test_containerlib_copyByPosition_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_sequence(){ doCompile("test_sequence"); check("intRes", Arrays.asList(0,1,2)); check("longRes", Arrays.asList(Long.valueOf(0),Long.valueOf(1),Long.valueOf(2))); check("stringRes", Arrays.asList("0","1","2")); check("intCurrent", Integer.valueOf(2)); check("longCurrent", Long.valueOf(2)); check("stringCurrent", "2"); } //TODO: If this test fails please double check whether the test is correct? public void test_lookup(){ doCompile("test_lookup"); check("alphaResult", Arrays.asList("Andorra la Vella","Andorra la Vella")); check("bravoResult", Arrays.asList("Bruxelles","Bruxelles")); check("charlieResult", Arrays.asList("Chamonix","Chodov","Chomutov","Chamonix","Chodov","Chomutov")); check("countResult", Arrays.asList(3,3)); check("charlieUpdatedCount", 5); check("charlieUpdatedResult", Arrays.asList("Chamonix", "Cheb", "Chodov", "Chomutov", "Chrudim")); check("putResult", true); check("meta", null); check("meta2", null); check("meta3", null); check("meta4", null); check("strRet", "Bratislava"); check("strRet2","Andorra la Vella"); check("intRet", 0); check("intRet2", 1); check("meta7", null); // CLO-1582 check("nonExistingKeyRecord", null); check("nullKeyRecord", null); check("unusedNext", getVariable("unusedNextExpected")); } public void test_lookup_expect_error(){ //CLO-1582 try { doCompile("function integer transform(){string str = lookup(TestLookup).get('Alpha',2).City; return 0;}","test_lookup_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer count = lookup(TestLookup).count('Alpha',1); printErr(count); lookup(TestLookup).next(); string city = lookup(TestLookup).next().City; return 0;}","test_lookup_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){lookupMetadata meta = null; lookup(TestLookup).put(meta); return 0;}","test_lookup_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){lookup(TestLookup).put(null); return 0;}","test_lookup_expect_error"); fail(); } catch (Exception e) { // do nothing } } //------------------------- ContainerLib Tests--------------------- public void test_containerlib_append() { doCompile("test_containerlib_append"); check("appendElem", Integer.valueOf(10)); check("appendList", Arrays.asList(1, 2, 3, 4, 5, 10)); check("stringList", Arrays.asList("horse","is","pretty","scary")); check("stringList2", Arrays.asList("horse", null)); check("stringList3", Arrays.asList("horse", "")); check("integerList1", Arrays.asList(1,2,3,4)); check("integerList2", Arrays.asList(1,2,null)); check("numberList1", Arrays.asList(0.21,1.1,2.2)); check("numberList2", Arrays.asList(1.1,null)); check("longList1", Arrays.asList(1l,2l,3L)); check("longList2", Arrays.asList(9L,null)); check("decList1", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("4.5"),new BigDecimal("6.7"))); check("decList2",Arrays.asList(new BigDecimal("1.1"), null)); } public void test_containerlib_append_expect_error(){ try { doCompile("function integer transform(){string[] listInput = null; append(listInput,'aa'); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte[] listInput = null; append(listInput,str2byte('third', 'utf-8')); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long[] listInput = null; append(listInput,15L); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] listInput = null; append(listInput,12); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal[] listInput = null; append(listInput,12.5d); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number[] listInput = null; append(listInput,12.36); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } } @SuppressWarnings("unchecked") public void test_containerlib_clear() { doCompile("test_containerlib_clear"); assertTrue(((List<Integer>) getVariable("integerList")).isEmpty()); assertTrue(((List<Integer>) getVariable("strList")).isEmpty()); assertTrue(((List<Integer>) getVariable("longList")).isEmpty()); assertTrue(((List<Integer>) getVariable("decList")).isEmpty()); assertTrue(((List<Integer>) getVariable("numList")).isEmpty()); assertTrue(((List<Integer>) getVariable("byteList")).isEmpty()); assertTrue(((List<Integer>) getVariable("dateList")).isEmpty()); assertTrue(((List<Integer>) getVariable("boolList")).isEmpty()); assertTrue(((List<Integer>) getVariable("emptyList")).isEmpty()); assertTrue(((Map<String,Integer>) getVariable("myMap")).isEmpty()); } public void test_container_clear_expect_error(){ try { doCompile("function integer transform(){boolean[] nullList = null; clear(nullList); return 0;}","test_container_clear_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[integer,string] myMap = null; clear(myMap); return 0;}","test_container_clear_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_copy() { doCompile("test_containerlib_copy"); check("copyIntList", Arrays.asList(1, 2, 3, 4, 5)); check("returnedIntList", Arrays.asList(1, 2, 3, 4, 5)); check("copyLongList", Arrays.asList(21L,15L, null, 10L)); check("returnedLongList", Arrays.asList(21l, 15l, null, 10L)); check("copyBoolList", Arrays.asList(false,false,null,true)); check("returnedBoolList", Arrays.asList(false,false,null,true)); Calendar cal = Calendar.getInstance(); cal.set(2006, 10, 12, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2002, 03, 12, 0, 0, 0); cal2.set(Calendar.MILLISECOND, 0); check("copyDateList",Arrays.asList(cal2.getTime(), null, cal.getTime())); check("returnedDateList",Arrays.asList(cal2.getTime(), null, cal.getTime())); check("copyStrList", Arrays.asList("Ashe", "Jax", null, "Rengar")); check("returnedStrList", Arrays.asList("Ashe", "Jax", null, "Rengar")); check("copyNumList", Arrays.asList(12.65d, 458.3d, null, 15.65d)); check("returnedNumList", Arrays.asList(12.65d, 458.3d, null, 15.65d)); check("copyDecList", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("5.9"), null, new BigDecimal("15.3"))); check("returnedDecList", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("5.9"), null, new BigDecimal("15.3"))); Map<String, String> expectedMap = new HashMap<String, String>(); expectedMap.put("a", "a"); expectedMap.put("b", "b"); expectedMap.put("c", "c"); expectedMap.put("d", "d"); check("copyStrMap", expectedMap); check("returnedStrMap", expectedMap); Map<Integer, Integer> intMap = new HashMap<Integer, Integer>(); intMap.put(1,12); intMap.put(2,null); intMap.put(3,15); check("copyIntMap", intMap); check("returnedIntMap", intMap); Map<Long, Long> longMap = new HashMap<Long, Long>(); longMap.put(10L, 453L); longMap.put(11L, null); longMap.put(12L, 54755L); check("copyLongMap", longMap); check("returnedLongMap", longMap); Map<BigDecimal, BigDecimal> decMap = new HashMap<BigDecimal, BigDecimal>(); decMap.put(new BigDecimal("2.2"), new BigDecimal("12.3")); decMap.put(new BigDecimal("2.3"), new BigDecimal("45.6")); check("copyDecMap", decMap); check("returnedDecMap", decMap); Map<Double, Double> doubleMap = new HashMap<Double, Double>(); doubleMap.put(new Double(12.3d), new Double(11.2d)); doubleMap.put(new Double(13.4d), new Double(78.9d)); check("copyNumMap",doubleMap); check("returnedNumMap", doubleMap); List<String> myList = new ArrayList<String>(); check("copyEmptyList", myList); check("returnedEmptyList", myList); assertTrue(((List<String>)(getVariable("copyEmptyList"))).isEmpty()); assertTrue(((List<String>)(getVariable("returnedEmptyList"))).isEmpty()); Map<String, String> emptyMap = new HashMap<String, String>(); check("copyEmptyMap", emptyMap); check("returnedEmptyMap", emptyMap); assertTrue(((HashMap<String,String>)(getVariable("copyEmptyMap"))).isEmpty()); assertTrue(((HashMap<String,String>)(getVariable("returnedEmptyMap"))).isEmpty()); } public void test_containerlib_copy_expect_error(){ try { doCompile("function integer transform(){string[] origList = null; string[] copyList; string[] ret = copy(copyList, origList); return 0;}","test_containerlib_copy_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] origList; string[] copyList = null; string[] ret = copy(copyList, origList); return 0;}","test_containerlib_copy_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string, string] orig = null; map[string, string] copy; map[string, string] ret = copy(copy, orig); return 0;}","test_containerlib_copy_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string, string] orig; map[string, string] copy = null; map[string, string] ret = copy(copy, orig); return 0;}","test_containerlib_copy_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_insert() { doCompile("test_containerlib_insert"); check("copyStrList",Arrays.asList("Elise","Volibear","Garen","Jarvan IV")); check("retStrList",Arrays.asList("Elise","Volibear","Garen","Jarvan IV")); check("copyStrList2", Arrays.asList("Jax", "Aatrox", "Lisandra", "Ashe")); check("retStrList2", Arrays.asList("Jax", "Aatrox", "Lisandra", "Ashe")); Calendar cal = Calendar.getInstance(); cal.set(2009, 10, 12, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal1 = Calendar.getInstance(); cal1.set(2008, 2, 7, 0, 0, 0); cal1.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2003, 01, 1, 0, 0, 0); cal2.set(Calendar.MILLISECOND, 0); check("copyDateList", Arrays.asList(cal1.getTime(),cal.getTime())); check("retDateList", Arrays.asList(cal1.getTime(),cal.getTime())); check("copyDateList2", Arrays.asList(cal2.getTime(),cal1.getTime(),cal.getTime())); check("retDateList2", Arrays.asList(cal2.getTime(),cal1.getTime(),cal.getTime())); check("copyIntList", Arrays.asList(1,2,3,12,4,5,6,7)); check("retIntList", Arrays.asList(1,2,3,12,4,5,6,7)); check("copyLongList", Arrays.asList(14L,15l,16l,17l)); check("retLongList", Arrays.asList(14L,15l,16l,17l)); check("copyLongList2", Arrays.asList(20L,21L,22L,23l)); check("retLongList2", Arrays.asList(20L,21L,22L,23l)); check("copyNumList", Arrays.asList(12.3d,11.1d,15.4d)); check("retNumList", Arrays.asList(12.3d,11.1d,15.4d)); check("copyNumList2", Arrays.asList(22.2d,44.4d,55.5d,33.3d)); check("retNumList2", Arrays.asList(22.2d,44.4d,55.5d,33.3d)); check("copyDecList", Arrays.asList(new BigDecimal("11.1"), new BigDecimal("22.2"), new BigDecimal("33.3"))); check("retDecList", Arrays.asList(new BigDecimal("11.1"), new BigDecimal("22.2"), new BigDecimal("33.3"))); check("copyDecList2",Arrays.asList(new BigDecimal("3.3"), new BigDecimal("4.4"), new BigDecimal("1.1"), new BigDecimal("2.2"))); check("retDecList2",Arrays.asList(new BigDecimal("3.3"), new BigDecimal("4.4"), new BigDecimal("1.1"), new BigDecimal("2.2"))); check("copyEmpty", Arrays.asList(11)); check("retEmpty", Arrays.asList(11)); check("copyEmpty2", Arrays.asList(12,13)); check("retEmpty2", Arrays.asList(12,13)); check("copyEmpty3", Arrays.asList()); check("retEmpty3", Arrays.asList()); } public void test_containerlib_insert_expect_error(){ try { doCompile("function integer transform(){integer[] tmp = null; integer[] ret = insert(tmp,0,12); return 0;}","test_containerlib_insert_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] tmp; integer[] toAdd = null; integer[] ret = insert(tmp,0,toAdd); return 0;}","test_containerlib_insert_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] tmp = [11,12]; integer[] ret = insert(tmp,-1,12); return 0;}","test_containerlib_insert_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] tmp = [11,12]; integer[] ret = insert(tmp,10,12); return 0;}","test_containerlib_insert_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_isEmpty() { doCompile("test_containerlib_isEmpty"); check("emptyMap", true); check("emptyMap1", true); check("fullMap", false); check("fullMap1", false); check("emptyList", true); check("emptyList1", true); check("fullList", false); check("fullList1", false); } public void test_containerlib_isEmpty_expect_error(){ try { doCompile("function integer transform(){integer[] i = null; boolean boo = i.isEmpty(); return 0;}","test_containerlib_isEmpty_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string, string] m = null; boolean boo = m.isEmpty(); return 0;}","test_containerlib_isEmpty_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_length(){ doCompile("test_containerlib_length"); check("lengthByte", 18); check("lengthByte2", 18); check("recordLength", 9); check("recordLength2", 9); check("listLength", 3); check("listLength2", 3); check("emptyListLength", 0); check("emptyListLength2", 0); check("emptyMapLength", 0); check("emptyMapLength2", 0); check("nullLength1", 0); check("nullLength2", 0); check("nullLength3", 0); check("nullLength4", 0); check("nullLength5", 0); check("nullLength6", 0); } public void test_containerlib_poll() throws UnsupportedEncodingException { doCompile("test_containerlib_poll"); check("intElem", Integer.valueOf(1)); check("intElem1", 2); check("intList", Arrays.asList(3, 4, 5)); check("strElem", "Zyra"); check("strElem2", "Tresh"); check("strList", Arrays.asList("Janna", "Wu Kong")); Calendar cal = Calendar.getInstance(); cal.set(2002, 10, 12, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); check("dateElem", cal.getTime()); cal.clear(); cal.set(2003,5,12,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("dateElem2", cal.getTime()); cal.clear(); cal.set(2006,9,15,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal.getTime())); checkArray("byteElem", "Maoki".getBytes("UTF-8")); checkArray("byteElem2", "Nasus".getBytes("UTF-8")); check("longElem", 12L); check("longElem2", 15L); check("longList", Arrays.asList(16L,23L)); check("numElem", 23.6d); check("numElem2", 15.9d); check("numList", Arrays.asList(78.8d, 57.2d)); check("decElem", new BigDecimal("12.3")); check("decElem2", new BigDecimal("23.4")); check("decList", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6"))); check("emptyElem", null); check("emptyElem2", null); check("emptyList", Arrays.asList()); } public void test_containerlib_poll_expect_error(){ try { doCompile("function integer transform(){integer[] arr = null; integer i = poll(arr); return 0;}","test_containerlib_poll_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] arr = null; integer i = arr.poll(); return 0;}","test_containerlib_poll_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_pop() { doCompile("test_containerlib_pop"); check("intElem", 5); check("intElem2", 4); check("intList", Arrays.asList(1, 2, 3)); check("longElem", 14L); check("longElem2", 13L); check("longList", Arrays.asList(11L,12L)); check("numElem", 11.5d); check("numElem2", 11.4d); check("numList", Arrays.asList(11.2d,11.3d)); check("decElem", new BigDecimal("22.5")); check("decElem2", new BigDecimal("22.4")); check("decList", Arrays.asList(new BigDecimal("22.2"), new BigDecimal("22.3"))); Calendar cal = Calendar.getInstance(); cal.set(2005, 8, 24, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); check("dateElem",cal.getTime()); cal.clear(); cal.set(2001, 6, 13, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); check("dateElem2", cal.getTime()); cal.clear(); cal.set(2010, 5, 11, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2011,3,3,0,0,0); cal2.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal.getTime(),cal2.getTime())); check("strElem", "Ezrael"); check("strElem2", null); check("strList", Arrays.asList("Kha-Zix", "Xerath")); check("emptyElem", null); check("emptyElem2", null); } public void test_containerlib_pop_expect_error(){ try { doCompile("function integer transform(){string[] arr = null; string str = pop(arr); return 0;}","test_containerlib_pop_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] arr = null; string str = arr.pop(); return 0;}","test_containerlib_pop_expect_error"); fail(); } catch (Exception e) { // do nothing } } @SuppressWarnings("unchecked") public void test_containerlib_push() { doCompile("test_containerlib_push"); check("intCopy", Arrays.asList(1, 2, 3)); check("intRet", Arrays.asList(1, 2, 3)); check("longCopy", Arrays.asList(12l,13l,14l)); check("longRet", Arrays.asList(12l,13l,14l)); check("numCopy", Arrays.asList(11.1d,11.2d,11.3d)); check("numRet", Arrays.asList(11.1d,11.2d,11.3d)); check("decCopy", Arrays.asList(new BigDecimal("12.2"), new BigDecimal("12.3"), new BigDecimal("12.4"))); check("decRet", Arrays.asList(new BigDecimal("12.2"), new BigDecimal("12.3"), new BigDecimal("12.4"))); check("strCopy", Arrays.asList("Fiora", "Nunu", "Amumu")); check("strRet", Arrays.asList("Fiora", "Nunu", "Amumu")); Calendar cal = Calendar.getInstance(); cal.set(2001, 5, 9, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal1 = Calendar.getInstance(); cal1.set(2005, 5, 9, 0, 0, 0); cal1.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2011, 5, 9, 0, 0, 0); cal2.set(Calendar.MILLISECOND, 0); check("dateCopy", Arrays.asList(cal.getTime(),cal1.getTime(),cal2.getTime())); check("dateRet", Arrays.asList(cal.getTime(),cal1.getTime(),cal2.getTime())); String str = null; check("emptyCopy", Arrays.asList(str)); check("emptyRet", Arrays.asList(str)); // there is hardly any way to get an instance of DataRecord // hence we just check if the list has correct size // and if its elements have correct metadata List<DataRecord> recordList = (List<DataRecord>) getVariable("recordList"); List<DataRecordMetadata> mdList = Arrays.asList( graph.getDataRecordMetadata(OUTPUT_1), graph.getDataRecordMetadata(INPUT_2), graph.getDataRecordMetadata(INPUT_1) ); assertEquals(mdList.size(), recordList.size()); for (int i = 0; i < mdList.size(); i++) { assertEquals(mdList.get(i), recordList.get(i).getMetadata()); } } public void test_containerlib_push_expect_error(){ try { doCompile("function integer transform(){string[] str = null; str.push('a'); return 0;}","test_containerlib_push_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] str = null; push(str, 'a'); return 0;}","test_containerlib_push_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_remove() { doCompile("test_containerlib_remove"); check("intElem", 2); check("intList", Arrays.asList(1, 3, 4, 5)); check("longElem", 13L); check("longList", Arrays.asList(11l,12l,14l)); check("numElem", 11.3d); check("numList", Arrays.asList(11.1d,11.2d,11.4d)); check("decElem", new BigDecimal("11.3")); check("decList", Arrays.asList(new BigDecimal("11.1"),new BigDecimal("11.2"),new BigDecimal("11.4"))); Calendar cal = Calendar.getInstance(); cal.set(2002,10,13,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("dateElem", cal.getTime()); cal.clear(); cal.set(2001,10,13,0,0,0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2003,10,13,0,0,0); cal2.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal.getTime(), cal2.getTime())); check("strElem", "Shivana"); check("strList", Arrays.asList("Annie","Lux")); } public void test_containerlib_remove_expect_error(){ try { doCompile("function integer transform(){string[] strList; string str = remove(strList,0); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] strList; string str = strList.remove(0); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] strList = ['Teemo']; string str = remove(strList,5); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] strList = ['Teemo']; string str = remove(strList,-1); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] strList = null; string str = remove(strList,0); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_reverse_expect_error(){ try { doCompile("function integer transform(){long[] longList = null; reverse(longList); return 0;}","test_containerlib_reverse_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){reverse(null); return 0;}","test_containerlib_reverse_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long[] longList = null; long[] reversed = longList.reverse(); return 0;}","test_containerlib_reverse_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_reverse() { doCompile("test_containerlib_reverse"); check("intList", Arrays.asList(5, 4, 3, 2, 1)); check("intList2", Arrays.asList(5, 4, 3, 2, 1)); check("longList", Arrays.asList(14l,13l,12l,11l)); check("longList2", Arrays.asList(14l,13l,12l,11l)); check("numList", Arrays.asList(1.3d,1.2d,1.1d)); check("numList2", Arrays.asList(1.3d,1.2d,1.1d)); check("decList", Arrays.asList(new BigDecimal("1.3"),new BigDecimal("1.2"),new BigDecimal("1.1"))); check("decList2", Arrays.asList(new BigDecimal("1.3"),new BigDecimal("1.2"),new BigDecimal("1.1"))); check("strList", Arrays.asList(null,"Lulu","Kog Maw")); check("strList2", Arrays.asList(null,"Lulu","Kog Maw")); Calendar cal = Calendar.getInstance(); cal.set(2001,2,1,0,0,0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2002,2,1,0,0,0); cal2.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal2.getTime(),cal.getTime())); check("dateList2", Arrays.asList(cal2.getTime(),cal.getTime())); } public void test_containerlib_sort() { doCompile("test_containerlib_sort"); check("intList", Arrays.asList(1, 1, 2, 3, 5)); check("intList2", Arrays.asList(1, 1, 2, 3, 5)); check("longList", Arrays.asList(21l,22l,23l,24l)); check("longList2", Arrays.asList(21l,22l,23l,24l)); check("decList", Arrays.asList(new BigDecimal("1.1"),new BigDecimal("1.2"),new BigDecimal("1.3"),new BigDecimal("1.4"))); check("decList2", Arrays.asList(new BigDecimal("1.1"),new BigDecimal("1.2"),new BigDecimal("1.3"),new BigDecimal("1.4"))); check("numList", Arrays.asList(1.1d,1.2d,1.3d,1.4d)); check("numList2", Arrays.asList(1.1d,1.2d,1.3d,1.4d)); Calendar cal = Calendar.getInstance(); cal.set(2002,5,12,0,0,0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2003,5,12,0,0,0); cal2.set(Calendar.MILLISECOND, 0); Calendar cal3 = Calendar.getInstance(); cal3.set(2004,5,12,0,0,0); cal3.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal.getTime(),cal2.getTime(),cal3.getTime())); check("dateList2", Arrays.asList(cal.getTime(),cal2.getTime(),cal3.getTime())); check("strList", Arrays.asList("","Alistar", "Nocturne", "Soraka")); check("strList2", Arrays.asList("","Alistar", "Nocturne", "Soraka")); check("emptyList", Arrays.asList()); check("emptyList2", Arrays.asList()); check("retNull1", Arrays.asList("Kennen", "Renector", null, null)); check("retNull2", Arrays.asList(false, true, true, null, null, null)); cal.clear(); cal.set(2001,0,20,0,0,0); cal.set(Calendar.MILLISECOND, 0); cal2.clear(); cal2.set(2003,4,12,0,0,0); cal2.set(Calendar.MILLISECOND, 0); check("retNull3", Arrays.asList(cal.getTime(), cal2.getTime(), null, null)); check("retNull4", Arrays.asList(1,8,10,12,null,null,null)); check("retNull5", Arrays.asList(1l, 12l, 15l, null, null, null)); check("retNull6", Arrays.asList(12.1d, 12.3d, 12.4d, null, null)); check("retNull7", Arrays.asList(new BigDecimal("11"), new BigDecimal("11.1"), new BigDecimal("11.2"), null, null, null)); } public void test_containerlib_sort_expect_error(){ try { doCompile("function integer transform(){string[] strList = null; sort(strList); return 0;}","test_containerlib_sort_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_containsAll() { doCompile("test_containerlib_containsAll"); check("results", Arrays.asList(true, false, true, false, true, true, true, false, true, true, false)); check("test1", true); check("test2", true); check("test3", true); check("test4", false); check("test5", true); check("test6", false); check("test7", true); check("test8", false); check("test9", true); check("test10", false); check("test11", true); check("test12", false); check("test13", false); check("test14", true); check("test15", false); check("test16", false); } public void test_containerlib_containsAll_expect_error(){ try { doCompile("function integer transform(){integer[] intList = null; boolean b =intList.containsAll([1]); return 0;}","test_containerlib_containsAll_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] intList; boolean b =intList.containsAll(null); return 0;}","test_containerlib_containsAll_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer[] intList; integer[] intList2 = null;" + "boolean b =intList.containsAll(intList2); return 0;}","test_containerlib_containsAll_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer[] intList = null; integer[] intList2 = null;" + "boolean b =intList.containsAll(intList2); return 0;}","test_containerlib_containsAll_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_containsKey() { doCompile("test_containerlib_containsKey"); check("results", Arrays.asList(false, true, false, true, false, true)); check("test1", true); check("test2", false); check("test3", true); check("test4", false); check("test5", true); check("test6", false); check("test7", true); check("test8", true); check("test9", true); check("test10", false); check("test11", true); check("test12", true); check("test13", false); check("test14", true); check("test15", true); check("test16", false); check("test17", true); check("test18", true); check("test19", false); check("test20", false); } public void test_containerlib_containsKey_expect_error(){ try { doCompile("function integer transform(){map[string, integer] emptyMap = null; boolean b = emptyMap.containsKey('a'); return 0;}","test_containerlib_containsKey_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_containsValue() { doCompile("test_containerlib_containsValue"); check("results", Arrays.asList(true, false, false, true, false, false, true, false)); check("test1", true); check("test2", true); check("test3", false); check("test4", true); check("test5", true); check("test6", false); check("test7", false); check("test8", true); check("test9", true); check("test10", false); check("test11", true); check("test12", true); check("test13", false); check("test14", true); check("test15", true); check("test16", false); check("test17", true); check("test18", true); check("test19", false); check("test20", true); check("test21", true); check("test22", false); check("test23", true); check("test24", true); check("test25", false); check("test26", false); } public void test_convertlib_containsValue_expect_error(){ try { doCompile("function integer transform(){map[integer, long] nullMap = null; boolean b = nullMap.containsValue(18L); return 0;}","test_convertlib_containsValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_getKeys() { doCompile("test_containerlib_getKeys"); check("stringList", Arrays.asList("a","b")); check("stringList2", Arrays.asList("a","b")); check("integerList", Arrays.asList(5,7,2)); check("integerList2", Arrays.asList(5,7,2)); List<Date> list = new ArrayList<Date>(); Calendar cal = Calendar.getInstance(); cal.set(2008, 10, 12, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2001, 5, 28, 0, 0, 0); cal2.set(Calendar.MILLISECOND, 0); list.add(cal.getTime()); list.add(cal2.getTime()); check("dateList", list); check("dateList2", list); check("longList", Arrays.asList(14L, 45L)); check("longList2", Arrays.asList(14L, 45L)); check("numList", Arrays.asList(12.3d, 13.4d)); check("numList2", Arrays.asList(12.3d, 13.4d)); check("decList", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6"))); check("decList2", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6"))); check("emptyList", Arrays.asList()); check("emptyList2", Arrays.asList()); } public void test_containerlib_getKeys_expect_error(){ try { doCompile("function integer transform(){map[string,string] strMap = null; string[] str = strMap.getKeys(); return 0;}","test_containerlib_getKeys_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string,string] strMap = null; string[] str = getKeys(strMap); return 0;}","test_containerlib_getKeys_expect_error"); fail(); } catch (Exception e) { // do nothing } } //---------------------- StringLib Tests ------------------------ public void test_stringlib_cache() { doCompile("test_stringlib_cache"); check("rep1", "The cat says meow. All cats say meow."); check("rep2", "The cat says meow. All cats say meow."); check("rep3", "The cat says meow. All cats say meow."); check("find1", Arrays.asList("to", "to", "to", "tro", "to")); check("find2", Arrays.asList("to", "to", "to", "tro", "to")); check("find3", Arrays.asList("to", "to", "to", "tro", "to")); check("split1", Arrays.asList("one", "two", "three", "four", "five")); check("split2", Arrays.asList("one", "two", "three", "four", "five")); check("split3", Arrays.asList("one", "two", "three", "four", "five")); check("chop01", "ting soming choping function"); check("chop02", "ting soming choping function"); check("chop03", "ting soming choping function"); check("chop11", "testing end of lines cutting"); check("chop12", "testing end of lines cutting"); } public void test_stringlib_charAt() { doCompile("test_stringlib_charAt"); String input = "The QUICk !!$ broWn fox juMPS over the lazy DOG "; String[] expected = new String[input.length()]; for (int i = 0; i < expected.length; i++) { expected[i] = String.valueOf(input.charAt(i)); } check("chars", Arrays.asList(expected)); } public void test_stringlib_charAt_error(){ //test: attempt to access char at position, which is out of bounds -> upper bound try { doCompile("string test;function integer transform(){test = charAt('milk', 7);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } //test: attempt to access char at position, which is out of bounds -> lower bound try { doCompile("string test;function integer transform(){test = charAt('milk', -1);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } //test: argument for position is null try { doCompile("string test; integer i = null; function integer transform(){test = charAt('milk', i);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } //test: input is null try { doCompile("string test;function integer transform(){test = charAt(null, 1);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } //test: input is empty string try { doCompile("string test;function integer transform(){test = charAt('', 1);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_concat() { doCompile("test_stringlib_concat"); final SimpleDateFormat format = new SimpleDateFormat(); format.applyPattern("yyyy MMM dd"); check("concat", ""); check("concat1", "ello hi ELLO 2,today is " + format.format(new Date())); check("concat2", ""); check("concat3", "clover"); check("test_null1", "null"); check("test_null2", "null"); check("test_null3","skynullisnullblue"); } public void test_stringlib_countChar() { doCompile("test_stringlib_countChar"); check("charCount", 3); check("count2", 0); } public void test_stringlib_countChar_emptychar() { // test: attempt to count empty chars in string. try { doCompile("integer charCount;function integer transform() {charCount = countChar('aaa','');return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } // test: attempt to count empty chars in empty string. try { doCompile("integer charCount;function integer transform() {charCount = countChar('','');return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } //test: null input - test 1 try { doCompile("integer charCount;function integer transform() {charCount = countChar(null,'a');return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } //test: null input - test 2 try { doCompile("integer charCount;function integer transform() {charCount = countChar(null,'');return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } //test: null input - test 3 try { doCompile("integer charCount;function integer transform() {charCount = countChar(null, null);return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_cut() { doCompile("test_stringlib_cut"); check("cutInput", Arrays.asList("a", "1edf", "h3ijk")); } public void test_string_cut_expect_error() { // test: Attempt to cut substring from position after the end of original string. E.g. string is 6 char long and // user attempt to cut out after position 8. try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[28,3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } // test: Attempt to cut substring longer then possible. E.g. string is 6 characters long and user cuts from // position // 4 substring 4 characters long try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,8]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } // test: Attempt to cut a substring with negative length try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,-3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } // test: Attempt to cut substring from negative position. E.g cut([-3,3]). try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[-3,3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: input is empty string try { doCompile("string input;string[] cutInput;function integer transform() {input = '';cutInput = cut(input,[0,3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: second arg is null try { doCompile("string input;string[] cutInput;function integer transform() {input = 'aaaa';cutInput = cut(input,null);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: input is null try { doCompile("string input;string[] cutInput;function integer transform() {input = null;cutInput = cut(input,[5,11]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_editDistance() { doCompile("test_stringlib_editDistance"); check("dist", 1); check("dist1", 1); check("dist2", 0); check("dist5", 1); check("dist3", 1); check("dist4", 0); check("dist6", 4); check("dist7", 5); check("dist8", 0); check("dist9", 0); } public void test_stringlib_editDistance_expect_error(){ //test: input - empty string - first arg try { doCompile("integer test;function integer transform() {test = editDistance('','mark');return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input - null - first arg try { doCompile("integer test;function integer transform() {test = editDistance(null,'mark');return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input- empty string - second arg try { doCompile("integer test;function integer transform() {test = editDistance('mark','');return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input - null - second argument try { doCompile("integer test;function integer transform() {test = editDistance('mark',null);return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input - both empty try { doCompile("integer test;function integer transform() {test = editDistance('','');return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input - both null try { doCompile("integer test;function integer transform() {test = editDistance(null,null);return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } } public void test_stringlib_find() { doCompile("test_stringlib_find"); check("findList", Arrays.asList("The quick br", "wn f", "x jumps ", "ver the lazy d", "g")); check("findList2", Arrays.asList("mark.twain")); check("findList3", Arrays.asList()); check("findList4", Arrays.asList("", "", "", "", "")); check("findList5", Arrays.asList("twain")); check("findList6", Arrays.asList("")); } public void test_stringlib_find_expect_error() { //test: regexp group number higher then count of regexp groups try { doCompile("string[] findList;function integer transform() {findList = find('[email protected]','(^[a-z]*).([a-z]*)',5); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: negative regexp group number try { doCompile("string[] findList;function integer transform() {findList = find('[email protected]','(^[a-z]*).([a-z]*)',-1); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: arg1 null input try { doCompile("string[] findList;function integer transform() {findList = find(null,'(^[a-z]*).([a-z]*)'); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: arg2 null input - test1 try { doCompile("string[] findList;function integer transform() {findList = find('[email protected]',null); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: arg2 null input - test2 try { doCompile("string[] findList;function integer transform() {findList = find('',null); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: arg1 and arg2 null input try { doCompile("string[] findList;function integer transform() {findList = find(null,null); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } } public void test_stringlib_join() { doCompile("test_stringlib_join"); //check("joinedString", "Bagr,3,3.5641,-87L,CTL2"); check("joinedString1", "80=5455.987\"-5=5455.987\"3=0.1"); check("joinedString2", "5.0♫54.65♫67.0♫231.0"); //check("joinedString3", "5☺54☺65☺67☺231☺80=5455.987☺-5=5455.987☺3=0.1☺CTL2☺42"); check("test_empty1", "abc"); check("test_empty2", ""); check("test_empty3"," "); check("test_empty4","anullb"); check("test_empty5","80=5455.987-5=5455.9873=0.1"); check("test_empty6","80=5455.987 -5=5455.987 3=0.1"); check("test_null1","abc"); check("test_null2",""); check("test_null3","anullb"); check("test_null4","80=5455.987-5=5455.9873=0.1"); //CLO-1210 check("test_empty7","a=xb=nullc=z"); check("test_empty8","a=x b=null c=z"); check("test_empty9","null=xeco=storm"); check("test_empty10","null=x eco=storm"); check("test_null5","a=xb=nullc=z"); check("test_null6","null=xeco=storm"); } public void test_stringlib_join_expect_error(){ // CLO-1567 - join("", null) is ambiguous // try { // doCompile("function integer transform(){string s = join(';',null);return 0;}","test_stringlib_join_expect_error"); // fail(); // } catch (Exception e) { // // do nothing // } try { doCompile("function integer transform(){string[] tmp = null; string s = join(';',tmp);return 0;}","test_stringlib_join_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string,string] a = null; string s = join(';',a);return 0;}","test_stringlib_join_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_left() { // CLO-1193 doCompile("test_stringlib_left"); check("test1", "aa"); check("test2", "aaa"); check("test3", ""); check("test4", null); check("test5", "abc"); check("test6", "ab "); check("test7", " "); check("test8", null); check("test9", "abc"); check("test10", "abc"); check("test11", ""); check("test12", null); check("test13", null); check("test14", ""); check("test15", ""); } public void test_stringlib_left_expect_error(){ try { doCompile("function integer transform(){string s = left('Lux', -7, false); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = left('Darius', -7, true); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = left('Darius', null, true); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer int = null; string s = left('Darius', int, true); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){boolean b = null; string s = left('Darius', 9, b); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = left('Darius', 7, null); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_length() { doCompile("test_stringlib_length"); check("lenght1", new BigDecimal(50)); check("stringLength", 8); check("length_empty", 0); check("length_null1", 0); } public void test_stringlib_lowerCase() { doCompile("test_stringlib_lowerCase"); check("lower", "the quick !!$ brown fox jumps over the lazy dog bagr "); check("lower_empty", ""); check("lower_null", null); } public void test_stringlib_matches() { doCompile("test_stringlib_matches"); check("matches1", true); check("matches2", true); check("matches3", false); check("matches4", true); check("matches5", false); check("matches6", false); check("matches7", false); check("matches8", false); check("matches9", true); check("matches10", true); } public void test_stringlib_matches_expect_error(){ //test: regexp param null - test 1 try { doCompile("boolean test; function integer transform(){test = matches('aaa', null); return 0;}","test_stringlib_matches_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp param null - test 2 try { doCompile("boolean test; function integer transform(){test = matches('', null); return 0;}","test_stringlib_matches_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp param null - test 3 try { doCompile("boolean test; function integer transform(){test = matches(null, null); return 0;}","test_stringlib_matches_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_matchGroups() { doCompile("test_stringlib_matchGroups"); check("result1", null); check("result2", Arrays.asList( //"(([^:]*)([:])([\\(]))(.*)(\\))(((#)(.*))|($))" "zip:(zip:(/path/name?.zip)#innerfolder/file.zip)#innermostfolder?/filename*.txt", "zip:(", "zip", ":", "(", "zip:(/path/name?.zip)#innerfolder/file.zip", ")", "#innermostfolder?/filename*.txt", "#innermostfolder?/filename*.txt", "#", "innermostfolder?/filename*.txt", null ) ); check("result3", null); check("test_empty1", null); check("test_empty2", Arrays.asList("")); check("test_null1", null); check("test_null2", null); } public void test_stringlib_matchGroups_expect_error(){ //test: regexp is null - test 1 try { doCompile("string[] test; function integer transform(){test = matchGroups('eat all the cookies',null); return 0;}","test_stringlib_matchGroups_expect_error"); } catch (Exception e) { // do nothing } //test: regexp is null - test 2 try { doCompile("string[] test; function integer transform(){test = matchGroups('',null); return 0;}","test_stringlib_matchGroups_expect_error"); } catch (Exception e) { // do nothing } //test: regexp is null - test 3 try { doCompile("string[] test; function integer transform(){test = matchGroups(null,null); return 0;}","test_stringlib_matchGroups_expect_error"); } catch (Exception e) { // do nothing } } public void test_stringlib_matchGroups_unmodifiable() { try { doCompile("test_stringlib_matchGroups_unmodifiable"); fail(); } catch (RuntimeException re) { }; } public void test_stringlib_metaphone() { doCompile("test_stringlib_metaphone"); check("metaphone1", "XRS"); check("metaphone2", "KWNTLN"); check("metaphone3", "KWNT"); check("metaphone4", ""); check("metaphone5", ""); check("test_empty1", ""); check("test_empty2", ""); check("test_null1", null); check("test_null2", null); } public void test_stringlib_nysiis() { doCompile("test_stringlib_nysiis"); check("nysiis1", "CAP"); check("nysiis2", "CAP"); check("nysiis3", "1234"); check("nysiis4", "C2 PRADACTAN"); check("nysiis_empty", ""); check("nysiis_null", null); } public void test_stringlib_replace() { doCompile("test_stringlib_replace"); final SimpleDateFormat format = new SimpleDateFormat(); format.applyPattern("yyyy MMM dd"); check("rep", format.format(new Date()).replaceAll("[lL]", "t")); check("rep1", "The cat says meow. All cats say meow."); check("rep2", "intruders must die"); check("test_empty1", "a"); check("test_empty2", ""); check("test_null", null); check("test_null2",""); check("test_null3","bbb"); check("test_null4",null); } public void test_stringlib_replace_expect_error(){ //test: regexp null - test1 try { doCompile("string test; function integer transform(){test = replace('a b',null,'b'); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp null - test2 try { doCompile("string test; function integer transform(){test = replace('',null,'b'); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp null - test3 try { doCompile("string test; function integer transform(){test = replace(null,null,'b'); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: arg3 null - test1 try { doCompile("string test; function integer transform(){test = replace('a b','a+',null); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } // //test: arg3 null - test2 // try { // doCompile("string test; function integer transform(){test = replace('','a+',null); return 0;}","test_stringlib_replace_expect_error"); // fail(); // } catch (Exception e) { // // do nothing // } // //test: arg3 null - test3 // try { // doCompile("string test; function integer transform(){test = replace(null,'a+',null); return 0;}","test_stringlib_replace_expect_error"); // fail(); // } catch (Exception e) { // // do nothing // } //test: regexp and arg3 null - test1 try { doCompile("string test; function integer transform(){test = replace('a b',null,null); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp and arg3 null - test1 try { doCompile("string test; function integer transform(){test = replace(null,null,null); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_right() { doCompile("test_stringlib_right"); check("righ", "y dog"); check("rightNotPadded", "y dog"); check("rightPadded", "y dog"); check("padded", " y dog"); check("notPadded", "y dog"); check("short", "Dog"); check("shortNotPadded", "Dog"); check("shortPadded", " Dog"); check("simple", "milk"); check("test_null1", null); check("test_null2", null); check("test_null3", " "); check("test_empty1", ""); check("test_empty2", ""); check("test_empty3"," "); } public void test_stringlib_soundex() { doCompile("test_stringlib_soundex"); check("soundex1", "W630"); check("soundex2", "W643"); check("test_null", null); check("test_empty", ""); } public void test_stringlib_split() { doCompile("test_stringlib_split"); check("split1", Arrays.asList("The quick br", "wn f", "", " jumps " , "ver the lazy d", "g")); check("test_empty", Arrays.asList("")); check("test_empty2", Arrays.asList("","a","a")); List<String> tmp = new ArrayList<String>(); tmp.add(null); check("test_null", tmp); } public void test_stringlib_split_expect_error(){ //test: regexp null - test1 try { doCompile("function integer transform(){string[] s = split('aaa',null); return 0;}","test_stringlib_split_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp null - test2 try { doCompile("function integer transform(){string[] s = split('',null); return 0;}","test_stringlib_split_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp null - test3 try { doCompile("function integer transform(){string[] s = split(null,null); return 0;}","test_stringlib_split_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_substring() { doCompile("test_stringlib_substring"); check("subs", "UICk "); check("test1", ""); check("test_empty", ""); } public void test_stringlib_substring_expect_error(){ try { doCompile("function integer transform(){string test = substring('arabela',4,19);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('arabela',15,3);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('arabela',2,-3);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('arabela',-5,7);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('',0,7);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('',7,7);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring(null,0,0);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring(null,0,4);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring(null,1,4);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_trim() { doCompile("test_stringlib_trim"); check("trim1", "im The QUICk !!$ broWn fox juMPS over the lazy DOG"); check("trim_empty", ""); check("trim_null", null); } public void test_stringlib_upperCase() { doCompile("test_stringlib_upperCase"); check("upper", "THE QUICK !!$ BROWN FOX JUMPS OVER THE LAZY DOG BAGR "); check("test_empty", ""); check("test_null", null); } public void test_stringlib_isFormat() { doCompile("test_stringlib_isFormat"); check("test", "test"); check("isBlank", Boolean.FALSE); check("blank", ""); checkNull("nullValue"); check("isBlank1", true); check("isBlank2", true); check("isAscii1", true); check("isAscii2", false); check("isAscii3", true); check("isAscii4", true); check("isNumber", false); check("isNumber1", false); check("isNumber2", true); check("isNumber3", true); check("isNumber4", false); check("isNumber5", true); check("isNumber6", true); check("isNumber7", false); check("isNumber8", false); check("isInteger", false); check("isInteger1", false); check("isInteger2", false); check("isInteger3", true); check("isInteger4", false); check("isInteger5", false); check("isLong", true); check("isLong1", false); check("isLong2", false); check("isLong3", false); check("isLong4", false); check("isDate", true); check("isDate1", false); // "kk" allows hour to be 1-24 (as opposed to HH allowing hour to be 0-23) check("isDate2", true); check("isDate3", true); check("isDate4", false); check("isDate5", true); check("isDate6", true); check("isDate7", false); // illegal month: 15 check("isDate9", false); check("isDate10", false); check("isDate11", false); check("isDate12", true); check("isDate13", false); // 24 is an illegal value for pattern HH (it allows only 0-23) check("isDate14", false); // empty string: invalid check("isDate15", false); check("isDate16", false); check("isDate17", true); check("isDate18", true); check("isDate19", false); check("isDate20", false); check("isDate21", false); // CLO-1190 check("isDate22", true); check("isDate23", false); check("isDate24", true); check("isDate25", false); check("isDate26", true); check("isDate27", true); } public void test_stringlib_empty_strings() { String[] expressions = new String[] { "isInteger(?)", "isNumber(?)", "isLong(?)", "isAscii(?)", "isBlank(?)", "isDate(?, \"yyyy\")", "isUrl(?)", "string x = ?; length(x)", "lowerCase(?)", "matches(?, \"\")", "NYSIIS(?)", "removeBlankSpace(?)", "removeDiacritic(?)", "removeNonAscii(?)", "removeNonPrintable(?)", "replace(?, \"a\", \"a\")", "translate(?, \"ab\", \"cd\")", "trim(?)", "upperCase(?)", "chop(?)", "concat(?)", "getAlphanumericChars(?)", }; StringBuilder sb = new StringBuilder(); for (String expr : expressions) { String emptyString = expr.replace("?", "\"\""); boolean crashesEmpty = test_expression_crashes(emptyString); assertFalse("Function " + emptyString + " crashed", crashesEmpty); String nullString = expr.replace("?", "null"); boolean crashesNull = test_expression_crashes(nullString); sb.append(String.format("|%20s|%5s|%5s|%n", expr, crashesEmpty ? "CRASH" : "ok", crashesNull ? "CRASH" : "ok")); } System.out.println(sb.toString()); } private boolean test_expression_crashes(String expr) { String expStr = "function integer transform() { " + expr + "; return 0; }"; try { doCompile(expStr, "test_stringlib_empty_null_strings"); return false; } catch (RuntimeException e) { return true; } } public void test_stringlib_removeBlankSpace() { String expStr = "string r1;\n" + "string str_empty;\n" + "string str_null;\n" + "function integer transform() {\n" + "r1=removeBlankSpace(\"" + StringUtils.specCharToString(" a b\nc\rd e \u000Cf\r\n") + "\");\n" + "printErr(r1);\n" + "str_empty = removeBlankSpace('');\n" + "str_null = removeBlankSpace(null);\n" + "return 0;\n" + "}\n"; doCompile(expStr, "test_removeBlankSpace"); check("r1", "abcdef"); check("str_empty", ""); check("str_null", null); } public void test_stringlib_removeNonPrintable() { doCompile("test_stringlib_removeNonPrintable"); check("nonPrintableRemoved", "AHOJ"); check("test_empty", ""); check("test_null", null); } public void test_stringlib_getAlphanumericChars() { String expStr = "string an1;\n " + "string an2;\n" + "string an3;\n" + "string an4;\n" + "string an5;\n" + "string an6;\n" + "string an7;\n" + "string an8;\n" + "string an9;\n" + "string an10;\n" + "string an11;\n" + "string an12;\n" + "string an13;\n" + "string an14;\n" + "string an15;\n" + "function integer transform() {\n" + "an1=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\");\n" + "an2=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,true);\n" + "an3=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,false);\n" + "an4=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",false,true);\n" + "an5=getAlphanumericChars(\"\");\n" + "an6=getAlphanumericChars(\"\",true,true);\n"+ "an7=getAlphanumericChars(\"\",true,false);\n"+ "an8=getAlphanumericChars(\"\",false,true);\n"+ "an9=getAlphanumericChars(null);\n" + "an10=getAlphanumericChars(null,false,false);\n" + "an11=getAlphanumericChars(null,true,false);\n" + "an12=getAlphanumericChars(null,false,true);\n" + "an13=getAlphanumericChars(' 0 ľeškó11');\n" + "an14=getAlphanumericChars(' 0 ľeškó11', false, false);\n" + //CLO-1174 "an15=getAlphanumericChars('" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "',false,false);\n" + "return 0;\n" + "}\n"; doCompile(expStr, "test_getAlphanumericChars"); check("an1", "a1bcde2f"); check("an2", "a1bcde2f"); check("an3", "abcdef"); check("an4", "12"); check("an5", ""); check("an6", ""); check("an7", ""); check("an8", ""); check("an9", null); check("an10", null); check("an11", null); check("an12", null); check("an13", "0ľeškó11"); check("an14"," 0 ľeškó11"); //CLO-1174 String tmp = StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n"); check("an15", tmp); } public void test_stringlib_indexOf(){ doCompile("test_stringlib_indexOf"); check("index",2); check("index1",9); check("index2",0); check("index3",-1); check("index4",6); check("index5",-1); check("index6",0); check("index7",4); check("index8",4); check("index9", -1); check("index10", 2); check("index_empty1", -1); check("index_empty2", 0); check("index_empty3", 0); check("index_empty4", -1); } public void test_stringlib_indexOf_expect_error(){ //test: second arg is null - test1 try { doCompile("integer index;function integer transform() {index = indexOf('hello world',null); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: second arg is null - test2 try { doCompile("integer index;function integer transform() {index = indexOf('',null); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: first arg is null - test1 try { doCompile("integer index;function integer transform() {index = indexOf(null,'a'); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: first arg is null - test2 try { doCompile("integer index;function integer transform() {index = indexOf(null,''); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: both args are null try { doCompile("integer index;function integer transform() {index = indexOf(null,null); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_removeDiacritic(){ doCompile("test_stringlib_removeDiacritic"); check("test","tescik"); check("test1","zabicka"); check("test_empty", ""); check("test_null", null); } public void test_stringlib_translate(){ doCompile("test_stringlib_translate"); check("trans","hippi"); check("trans1","hipp"); check("trans2","hippi"); check("trans3",""); check("trans4","y lanuaX nXXd thX lXttXr X"); check("trans5", "hello"); check("test_empty1", ""); check("test_empty2", ""); check("test_null", null); } public void test_stringlib_translate_expect_error(){ try { doCompile("function integer transform(){string test = translate('bla bla',null,'o');return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate('bla bla','a',null);return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate('bla bla',null,null);return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate(null,'a',null);return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate(null,null,'a');return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate(null,null,null);return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_removeNonAscii(){ doCompile("test_stringlib_removeNonAscii"); check("test1", "Sun is shining"); check("test2", ""); check("test_empty", ""); check("test_null", null); } public void test_stringlib_chop() { doCompile("test_stringlib_chop"); check("s1", "hello"); check("s6", "hello"); check("s5", "hello"); check("s2", "hello"); check("s7", "helloworld"); check("s3", "hello "); check("s4", "hello"); check("s8", "hello"); check("s9", "world"); check("s10", "hello"); check("s11", "world"); check("s12", "mark.twain"); check("s13", "two words"); check("s14", ""); check("s15", ""); check("s16", ""); check("s17", ""); check("s18", ""); check("s19", "word"); check("s20", ""); check("s21", ""); check("s22", "mark.twain"); } public void test_stringlib_chop_expect_error() { //test: arg is null try { doCompile("string test;function integer transform() {test = chop(null);return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp pattern is null try { doCompile("string test;function integer transform() {test = chop('aaa', null);return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp pattern is null - test 2 try { doCompile("string test;function integer transform() {test = chop('', null);return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: arg is null try { doCompile("string test;function integer transform() {test = chop(null, 'aaa');return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: arg is null - test2 try { doCompile("string test;function integer transform() {test = chop(null, '');return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: arg is null - test3 try { doCompile("string test;function integer transform() {test = chop(null, null);return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } } //-------------------------- MathLib Tests ------------------------ public void test_bitwise_bitSet(){ doCompile("test_bitwise_bitSet"); check("test1", 3); check("test2", 15); check("test3", 34); check("test4", 3l); check("test5", 15l); check("test6", 34l); } public void test_bitwise_bitSet_expect_error(){ try { doCompile("function integer transform(){" + "integer var1 = null;" + "integer var2 = 3;" + "boolean var3 = false;" + "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer var1 = 512;" + "integer var2 = null;" + "boolean var3 = false;" + "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer var1 = 512;" + "integer var2 = 3;" + "boolean var3 = null;" + "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = 512l;" + "integer var2 = 3;" + "boolean var3 = null;" + "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = 512l;" + "integer var2 = null;" + "boolean var3 = true;" + "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = null;" + "integer var2 = 3;" + "boolean var3 = true;" + "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_bitIsSet(){ doCompile("test_bitwise_bitIsSet"); check("test1", true); check("test2", false); check("test3", false); check("test4", false); check("test5", true); check("test6", false); check("test7", false); check("test8", false); } public void test_bitwise_bitIsSet_expect_error(){ try { doCompile("function integer transform(){integer i = null; boolean b = bitIsSet(i,3); return 0;}","test_bitwise_bitIsSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = null; boolean b = bitIsSet(11,i); return 0;}","test_bitwise_bitIsSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = null; boolean b = bitIsSet(i,3); return 0;}","test_bitwise_bitIsSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = 12l; boolean b = bitIsSet(i,null); return 0;}","test_bitwise_bitIsSet_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_or() { doCompile("test_bitwise_or"); check("resultInt1", 1); check("resultInt2", 1); check("resultInt3", 3); check("resultInt4", 3); check("resultLong1", 1l); check("resultLong2", 1l); check("resultLong3", 3l); check("resultLong4", 3l); check("resultMix1", 15L); check("resultMix2", 15L); } public void test_bitwise_or_expect_error(){ try { doCompile("function integer transform(){" + "integer input1 = 12; " + "integer input2 = null; " + "integer i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer input1 = null; " + "integer input2 = 13; " + "integer i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long input1 = null; " + "long input2 = 13l; " + "long i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long input1 = 23l; " + "long input2 = null; " + "long i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_and() { doCompile("test_bitwise_and"); check("resultInt1", 0); check("resultInt2", 1); check("resultInt3", 0); check("resultInt4", 1); check("resultLong1", 0l); check("resultLong2", 1l); check("resultLong3", 0l); check("resultLong4", 1l); check("test_mixed1", 4l); check("test_mixed2", 4l); } public void test_bitwise_and_expect_error(){ try { doCompile("function integer transform(){\n" + "integer a = null; integer b = 16;\n" + "integer i = bitAnd(a,b);\n" + "return 0;}", "test_bitwise_end_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "integer a = 16; integer b = null;\n" + "integer i = bitAnd(a,b);\n" + "return 0;}", "test_bitwise_end_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "long a = 16l; long b = null;\n" + "long i = bitAnd(a,b);\n" + "return 0;}", "test_bitwise_end_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "long a = null; long b = 10l;\n" + "long i = bitAnd(a,b);\n" + "return 0;}", "test_bitwise_end_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_xor() { doCompile("test_bitwise_xor"); check("resultInt1", 1); check("resultInt2", 0); check("resultInt3", 3); check("resultInt4", 2); check("resultLong1", 1l); check("resultLong2", 0l); check("resultLong3", 3l); check("resultLong4", 2l); check("test_mixed1", 15L); check("test_mixed2", 60L); } public void test_bitwise_xor_expect_error(){ try { doCompile("function integer transform(){" + "integer var1 = null;" + "integer var2 = 123;" + "integer i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer var1 = 23;" + "integer var2 = null;" + "integer i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = null;" + "long var2 = 123l;" + "long i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = 2135l;" + "long var2 = null;" + "long i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_lshift() { doCompile("test_bitwise_lshift"); check("resultInt1", 2); check("resultInt2", 4); check("resultInt3", 10); check("resultInt4", 20); check("resultInt5", -2147483648); check("resultLong1", 2l); check("resultLong2", 4l); check("resultLong3", 10l); check("resultLong4", 20l); check("resultLong5",-9223372036854775808l); check("test_mixed1", 176l); check("test_mixed2", 616l); } public void test_bitwise_lshift_expect_error(){ try { doCompile("function integer transform(){integer input = null; integer i = bitLShift(input,2); return 0;}","test_bitwise_lshift_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer input = null; integer i = bitLShift(44,input); return 0;}","test_bitwise_lshift_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; long i = bitLShift(input,4l); return 0;}","test_bitwise_lshift_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; long i = bitLShift(444l,input); return 0;}","test_bitwise_lshift_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_rshift() { doCompile("test_bitwise_rshift"); check("resultInt1", 2); check("resultInt2", 0); check("resultInt3", 4); check("resultInt4", 2); check("resultLong1", 2l); check("resultLong2", 0l); check("resultLong3", 4l); check("resultLong4", 2l); check("test_neg1", 0); check("test_neg2", 0); check("test_neg3", 0l); check("test_neg4", 0l); // CLO-1399 check("test_mix1", 30l); check("test_mix2", 39l); } public void test_bitwise_rshift_expect_error(){ try { doCompile("function integer transform(){" + "integer var1 = 23;" + "integer var2 = null;" + "integer i = bitRShift(var1,var2);" + "return 0;}","test_bitwise_rshift_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){" + "integer var1 = null;" + "integer var2 = 78;" + "integer u = bitRShift(var1,var2);" + "return 0;}","test_bitwise_rshift_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){" + "long var1 = 23l;" + "long var2 = null;" + "long l =bitRShift(var1,var2);" + "return 0;}","test_bitwise_rshift_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){" + "long var1 = null;" + "long var2 = 84l;" + "long l = bitRShift(var1,var2);" + "return 0;}","test_bitwise_rshift_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_bitwise_negate() { doCompile("test_bitwise_negate"); check("resultInt", -59081717); check("resultLong", -3321654987654105969L); check("test_zero_int", -1); check("test_zero_long", -1l); } public void test_bitwise_negate_expect_error(){ try { doCompile("function integer transform(){integer input = null; integer i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; long i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_set_bit() { doCompile("test_set_bit"); check("resultInt1", 0x2FF); check("resultInt2", 0xFB); check("resultLong1", 0x4000000000000l); check("resultLong2", 0xFFDFFFFFFFFFFFFl); check("resultBool1", true); check("resultBool2", false); check("resultBool3", true); check("resultBool4", false); } public void test_mathlib_abs() { doCompile("test_mathlib_abs"); check("absIntegerPlus", new Integer(10)); check("absIntegerMinus", new Integer(1)); check("absLongPlus", new Long(10)); check("absLongMinus", new Long(1)); check("absDoublePlus", new Double(10.0)); check("absDoubleMinus", new Double(1.0)); check("absDecimalPlus", new BigDecimal(5.0)); check("absDecimalMinus", new BigDecimal(5.0)); } public void test_mathlib_abs_expect_error(){ try { doCompile("function integer transform(){ \n " + "integer tmp;\n " + "tmp = null; \n" + " integer i = abs(tmp); \n " + "return 0;}", "test_mathlib_abs_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){ \n " + "long tmp;\n " + "tmp = null; \n" + "long i = abs(tmp); \n " + "return 0;}", "test_mathlib_abs_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){ \n " + "double tmp;\n " + "tmp = null; \n" + "double i = abs(tmp); \n " + "return 0;}", "test_mathlib_abs_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){ \n " + "decimal tmp;\n " + "tmp = null; \n" + "decimal i = abs(tmp); \n " + "return 0;}", "test_mathlib_abs_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_ceil() { doCompile("test_mathlib_ceil"); check("ceil1", -3.0); check("intResult", Arrays.asList(2.0, 3.0)); check("longResult", Arrays.asList(2.0, 3.0)); check("doubleResult", Arrays.asList(3.0, -3.0)); check("decimalResult", Arrays.asList(new BigDecimal(3.0), new BigDecimal(-3.0))); } public void test_mathlib_ceil_expect_error(){ try { doCompile("function integer transform(){integer var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal var = null; decimal d = ceil(var); return 0;}","test_mathlib_ceil_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_e() { doCompile("test_mathlib_e"); check("varE", Math.E); } public void test_mathlib_exp() { doCompile("test_mathlib_exp"); check("ex", Math.exp(1.123)); check("test1", Math.exp(2)); check("test2", Math.exp(22)); check("test3", Math.exp(23)); check("test4", Math.exp(94)); } public void test_mathlib_exp_expect_error(){ try { doCompile("function integer transform(){integer input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_floor() { doCompile("test_mathlib_floor"); check("floor1", -4.0); check("intResult", Arrays.asList(2.0, 3.0)); check("longResult", Arrays.asList(2.0, 3.0)); check("doubleResult", Arrays.asList(2.0, -4.0)); check("decimalResult", Arrays.asList(new BigDecimal("2"), new BigDecimal("-4"))); } public void test_math_lib_floor_expect_error(){ try { doCompile("function integer transform(){integer input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input= null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; decimal d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_log() { doCompile("test_mathlib_log"); check("ln", Math.log(3)); check("test_int", Math.log(32)); check("test_long", Math.log(14l)); check("test_double", Math.log(12.9)); check("test_decimal", Math.log(23.7)); } public void test_math_log_expect_error(){ try { doCompile("function integer transform(){integer input = null; number n = log(input); return 0;}","test_math_log_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){long input = null; number n = log(input); return 0;}","test_math_log_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){decimal input = null; number n = log(input); return 0;}","test_math_log_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){double input = null; number n = log(input); return 0;}","test_math_log_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_mathlib_log10() { doCompile("test_mathlib_log10"); check("varLog10", Math.log10(3)); check("test_int", Math.log10(5)); check("test_long", Math.log10(90L)); check("test_decimal", Math.log10(32.1)); check("test_number", Math.log10(84.12)); } public void test_mathlib_log10_expect_error(){ try { doCompile("function integer transform(){integer input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_pi() { doCompile("test_mathlib_pi"); check("varPi", Math.PI); } public void test_mathlib_pow() { doCompile("test_mathlib_pow"); check("power1", Math.pow(3,1.2)); check("power2", Double.NaN); check("intResult", Arrays.asList(new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"))); check("longResult", Arrays.asList(new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"))); check("doubleResult", Arrays.asList(new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"))); check("decimalResult", Arrays.asList(new BigDecimal("8.000"), new BigDecimal("8.000"), new BigDecimal("8.000"), new BigDecimal("8.000"))); } public void test_mathlib_pow_expect_error(){ try { doCompile("function integer transform(){integer var1 = 12; integer var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer var1 = null; integer var2 = 2; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long var1 = 12l; long var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long var1 = null; long var2 = 12L; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number var1 = 12.2; number var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number var1 = null; number var2 = 2.1; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal var1 = 12.2d; decimal var2 = null; decimal n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal var1 = null; decimal var2 = 45.3d; decimal n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } } /* * The equals() method also takes the scale into account, * CTL uses compareTo() instead. */ private void compareDecimals(List<BigDecimal> expected, List<BigDecimal> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < actual.size(); i++) { assertTrue("Expected: " + expected.get(i) + ", actual: " + actual.get(i), expected.get(i).compareTo(actual.get(i)) == 0); } } @SuppressWarnings("unchecked") public void test_mathlib_round() { doCompile("test_mathlib_round"); check("round1", -4l); check("intResult", Arrays.asList(2l, 3l)); check("longResult", Arrays.asList(2l, 3l)); check("doubleResult", Arrays.asList(2l, 4l)); //CLO-1835 // check("decimalResult", Arrays.asList(new BigDecimal("2"), new BigDecimal("4"))); // negative precision means the number of places after the decimal point // positive precision before the decimal point List<BigDecimal> expected = Arrays.asList( new BigDecimal("1234567.1234567"), new BigDecimal("1234567.123457"), // rounded up new BigDecimal("1234567.12346"), // rounded up new BigDecimal("1234567.1235"), // rounded up new BigDecimal("1234567.123"), new BigDecimal("1234567.12"), new BigDecimal("1234567.1"), new BigDecimal("1234567"), new BigDecimal("1234570"), // rounded up new BigDecimal("1234600"), // rounded up new BigDecimal("1235000"), // rounded up new BigDecimal("1230000"), new BigDecimal("1200000"), new BigDecimal("1000000"), new BigDecimal("0") ); //CLO-1835 // compareDecimals(expected, (List<BigDecimal>) getVariable("decimal2Result")); //CLO-1832 // check("intWithPrecisionResult", 1200); // check("longWithPrecisionResult", 123500L); } public void test_mathlib_round_expect_error(){ try { doCompile("function integer transform(){number input = null; long l = round(input);return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; decimal l = round(input);return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_sqrt() { doCompile("test_mathlib_sqrt"); check("sqrtPi", Math.sqrt(Math.PI)); check("sqrt9", Math.sqrt(9)); check("test_int", 2.0); check("test_long", Math.sqrt(64L)); check("test_num", Math.sqrt(86.9)); check("test_dec", Math.sqrt(34.5)); } public void test_mathlib_sqrt_expect_error(){ try { doCompile("function integer transform(){integer input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_randomInteger(){ doCompile("test_mathlib_randomInteger"); assertNotNull(getVariable("test1")); check("test2", 2); } public void test_mathlib_randomInteger_expect_error(){ try { doCompile("function integer transform(){integer i = randomInteger(1,null); return 0;}","test_mathlib_randomInteger_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = randomInteger(null,null); return 0;}","test_mathlib_randomInteger_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = randomInteger(null, -3); return 0;}","test_mathlib_randomInteger_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = randomInteger(1,-7); return 0;}","test_mathlib_randomInteger_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_randomLong(){ doCompile("test_mathlib_randomLong"); assertNotNull(getVariable("test1")); check("test2", 15L); } public void test_mathlib_randomLong_expect_error(){ try { doCompile("function integer transform(){long lo = randomLong(15L, null); return 0;}","test_mathlib_randomLong_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long lo = randomLong(null, null); return 0;}","test_mathlib_randomLong_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long lo = randomLong(null, 15L); return 0;}","test_mathlib_randomLong_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long lo = randomLong(15L, 10L); return 0;}","test_mathlib_randomLong_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_setRandomSeed_expect_error(){ try { doCompile("function integer transform(){long l = null; setRandomSeed(l); return 0;}","test_mathlib_setRandomSeed_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = null; setRandomSeed(i); return 0;}","test_mathlib_setRandomSeed_expect_error"); fail(); } catch (Exception e) { // do nothing } } //-------------------------DateLib tests---------------------- public void test_datelib_cache() { doCompile("test_datelib_cache"); check("b11", true); check("b12", true); check("b21", true); check("b22", true); check("b31", true); check("b32", true); check("b41", true); check("b42", true); checkEquals("date3", "date3d"); checkEquals("date4", "date4d"); checkEquals("date7", "date7d"); checkEquals("date8", "date8d"); } public void test_datelib_trunc() { doCompile("test_datelib_trunc"); check("truncDate", new GregorianCalendar(2004, 00, 02).getTime()); } public void test_datelib_trunc_except_error(){ try { doCompile("function integer transform(){trunc(null); return 0;}","test_datelib_trunc_except_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = null; trunc(d); return 0;}","test_datelib_trunc_except_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_truncDate() { doCompile("test_datelib_truncDate"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)}; cal.clear(); cal.set(Calendar.HOUR_OF_DAY, portion[0]); cal.set(Calendar.MINUTE, portion[1]); cal.set(Calendar.SECOND, portion[2]); cal.set(Calendar.MILLISECOND, portion[3]); check("truncBornDate", cal.getTime()); } public void test_datelib_truncDate_except_error(){ try { doCompile("function integer transform(){truncDate(null); return 0;}","test_datelib_truncDate_except_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = null; truncDate(d); return 0;}","test_datelib_truncDate_except_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_today() { doCompile("test_datelib_today"); Date expectedDate = new Date(); //the returned date does not need to be exactly the same date which is in expectedData variable //let say 1000ms is tolerance for equality assertTrue("todayDate", Math.abs(expectedDate.getTime() - ((Date) getVariable("todayDate")).getTime()) < 1000); } public void test_datelib_zeroDate() { doCompile("test_datelib_zeroDate"); check("zeroDate", new Date(0)); } public void test_datelib_dateDiff() { doCompile("test_datelib_dateDiff"); long diffYears = Years.yearsBetween(new DateTime(), new DateTime(BORN_VALUE)).getYears(); check("ddiff", diffYears); long[] results = {1, 12, 52, 365, 8760, 525600, 31536000, 31536000000L}; String[] vars = {"ddiffYears", "ddiffMonths", "ddiffWeeks", "ddiffDays", "ddiffHours", "ddiffMinutes", "ddiffSeconds", "ddiffMilliseconds"}; for (int i = 0; i < results.length; i++) { check(vars[i], results[i]); } } public void test_datelib_dateDiff_epect_error(){ try { doCompile("function integer transform(){long i = dateDiff(null,today(),millisec);return 0;}","test_datelib_dateDiff_epect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = dateDiff(today(),null,millisec);return 0;}","test_datelib_dateDiff_epect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = dateDiff(today(),today(),null);return 0;}","test_datelib_dateDiff_epect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_dateAdd() { doCompile("test_datelib_dateAdd"); check("datum", new Date(BORN_MILLISEC_VALUE + 100)); } public void test_datelib_dateAdd_expect_error(){ try { doCompile("function integer transform(){date d = dateAdd(null,120,second); return 0;}","test_datelib_dateAdd_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = dateAdd(today(),null,second); return 0;}","test_datelib_dateAdd_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = dateAdd(today(),120,null); return 0;}","test_datelib_dateAdd_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_extractTime() { doCompile("test_datelib_extractTime"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)}; cal.clear(); cal.set(Calendar.HOUR_OF_DAY, portion[0]); cal.set(Calendar.MINUTE, portion[1]); cal.set(Calendar.SECOND, portion[2]); cal.set(Calendar.MILLISECOND, portion[3]); check("bornExtractTime", cal.getTime()); check("originalDate", BORN_VALUE); check("nullDate", null); check("nullDate2", null); } public void test_datelib_extractDate() { doCompile("test_datelib_extractDate"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); int[] portion = new int[]{cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH), cal.get(Calendar.YEAR)}; cal.clear(); cal.set(Calendar.DAY_OF_MONTH, portion[0]); cal.set(Calendar.MONTH, portion[1]); cal.set(Calendar.YEAR, portion[2]); check("bornExtractDate", cal.getTime()); check("originalDate", BORN_VALUE); check("nullDate", null); check("nullDate2", null); } public void test_datelib_createDate() { doCompile("test_datelib_createDate"); Calendar cal = Calendar.getInstance(); // no time zone cal.clear(); cal.set(2013, 5, 11); check("date1", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); check("dateTime1", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); cal.set(Calendar.MILLISECOND, 123); check("dateTimeMillis1", cal.getTime()); // literal cal.setTimeZone(TimeZone.getTimeZone("GMT+5")); cal.clear(); cal.set(2013, 5, 11); check("date2", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); check("dateTime2", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); cal.set(Calendar.MILLISECOND, 123); check("dateTimeMillis2", cal.getTime()); // variable cal.clear(); cal.set(2013, 5, 11); check("date3", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); check("dateTime3", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); cal.set(Calendar.MILLISECOND, 123); check("dateTimeMillis3", cal.getTime()); Calendar cal1 = Calendar.getInstance(); cal1.set(2011, 10, 20, 0, 0, 0); cal1.set(Calendar.MILLISECOND, 0); Date d = cal1.getTime(); // CLO-1674 check("ret1", d); check("ret2", d); cal1.clear(); cal1.set(2011, 10, 20, 4, 20, 11); cal1.set(Calendar.MILLISECOND, 0); check("ret3", cal1.getTime()); cal1.clear(); cal1.set(2011, 10, 20, 4, 20, 11); cal1.set(Calendar.MILLISECOND, 123); d = cal1.getTime(); check("ret4", d); // CLO-1674 check("ret5", d); } public void test_datelib_createDate_expect_error(){ try { doCompile("function integer transform(){date d = createDate(null, null, null); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, null, null); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, 10, null); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, 11, 20, null, 5, 45); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, 11, 20, 12, null, 45); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, 11, 20, 12, 5, null); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer str = null; date d = createDate(1970, 11, 20, 12, 5, 45, str); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_getPart() { doCompile("test_datelib_getPart"); Calendar cal = Calendar.getInstance(); cal.clear(); cal.setTimeZone(TimeZone.getTimeZone("GMT+1")); cal.set(2013, 5, 11, 14, 46, 34); cal.set(Calendar.MILLISECOND, 123); Date date = cal.getTime(); cal = Calendar.getInstance(); cal.setTime(date); // no time zone check("year1", cal.get(Calendar.YEAR)); check("month1", cal.get(Calendar.MONTH) + 1); check("day1", cal.get(Calendar.DAY_OF_MONTH)); check("hour1", cal.get(Calendar.HOUR_OF_DAY)); check("minute1", cal.get(Calendar.MINUTE)); check("second1", cal.get(Calendar.SECOND)); check("millisecond1", cal.get(Calendar.MILLISECOND)); cal.setTimeZone(TimeZone.getTimeZone("GMT+5")); // literal check("year2", cal.get(Calendar.YEAR)); check("month2", cal.get(Calendar.MONTH) + 1); check("day2", cal.get(Calendar.DAY_OF_MONTH)); check("hour2", cal.get(Calendar.HOUR_OF_DAY)); check("minute2", cal.get(Calendar.MINUTE)); check("second2", cal.get(Calendar.SECOND)); check("millisecond2", cal.get(Calendar.MILLISECOND)); // variable check("year3", cal.get(Calendar.YEAR)); check("month3", cal.get(Calendar.MONTH) + 1); check("day3", cal.get(Calendar.DAY_OF_MONTH)); check("hour3", cal.get(Calendar.HOUR_OF_DAY)); check("minute3", cal.get(Calendar.MINUTE)); check("second3", cal.get(Calendar.SECOND)); check("millisecond3", cal.get(Calendar.MILLISECOND)); check("year_null", 2013); check("month_null", 6); check("day_null", 11); check("hour_null", 15); check("minute_null", cal.get(Calendar.MINUTE)); check("second_null", cal.get(Calendar.SECOND)); check("milli_null", cal.get(Calendar.MILLISECOND)); check("year_null2", null); check("month_null2", null); check("day_null2", null); check("hour_null2", null); check("minute_null2", null); check("second_null2", null); check("milli_null2", null); check("year_null3", null); check("month_null3", null); check("day_null3", null); check("hour_null3", null); check("minute_null3", null); check("second_null3", null); check("milli_null3", null); } public void test_datelib_randomDate() { doCompile("test_datelib_randomDate"); final long HOUR = 60L * 60L * 1000L; Date BORN_VALUE_NO_MILLIS = new Date(BORN_VALUE.getTime() / 1000L * 1000L); check("noTimeZone1", BORN_VALUE); check("noTimeZone2", BORN_VALUE_NO_MILLIS); check("withTimeZone1", new Date(BORN_VALUE_NO_MILLIS.getTime() + 2*HOUR)); // timezone changes from GMT+5 to GMT+3 check("withTimeZone2", new Date(BORN_VALUE_NO_MILLIS.getTime() - 2*HOUR)); // timezone changes from GMT+3 to GMT+5 assertNotNull(getVariable("patt_null")); assertNotNull(getVariable("ret1")); assertNotNull(getVariable("ret2")); } public void test_datelib_randomDate_expect_error(){ try { doCompile("function integer transform(){date a = null; date b = today(); " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date a = today(); date b = null; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date a = null; date b = null; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long a = 843484317231l; long b = null; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long a = null; long b = 12115641158l; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long a = null; long b = null; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "string a = null; string b = '2006-11-12'; string pattern='yyyy-MM-dd';" + "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "string a = '2006-11-12'; string b = null; string pattern='yyyy-MM-dd';" + "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } //wrong format try { doCompile("function integer transform(){" + "string a = '2006-10-12'; string b = '2006-11-12'; string pattern='yyyy:MM:dd';" + "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } //start date bigger then end date try { doCompile("function integer transform(){" + "string a = '2008-10-12'; string b = '2006-11-12'; string pattern='yyyy-MM-dd';" + "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } } //-----------------Convert Lib tests----------------------- public void test_convertlib_json2xml(){ doCompile("test_convertlib_json2xml"); String xmlChunk ="" + "<lastName>Smith</lastName>" + "<phoneNumber>" + "<number>212 555-1234</number>" + "<type>home</type>" + "</phoneNumber>" + "<phoneNumber>" + "<number>646 555-4567</number>" + "<type>fax</type>" + "</phoneNumber>" + "<address>" + "<streetAddress>21 2nd Street</streetAddress>" + "<postalCode>10021</postalCode>" + "<state>NY</state>" + "<city>New York</city>" + "</address>" + "<age>25</age>" + "<firstName>John</firstName>"; check("ret", xmlChunk); check("ret2", "<name/>"); check("ret3", "<address></address>"); check("ret4", "</>"); check("ret5", "<#/>"); check("ret6", "</>/<//>"); check("ret7",""); check("ret8", "<>Urgot</>"); } public void test_convertlib_json2xml_expect_error(){ try { doCompile("function integer transform(){string str = json2xml(''); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string str = json2xml(null); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string str = json2xml('{\"name\"}'); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string str = json2xml('{\"name\":}'); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string str = json2xml('{:\"name\"}'); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_convertlib_xml2json(){ doCompile("test_convertlib_xml2json"); String json = "{\"lastName\":\"Smith\",\"phoneNumber\":[{\"number\":\"212 555-1234\",\"type\":\"home\"},{\"number\":\"646 555-4567\",\"type\":\"fax\"}],\"address\":{\"streetAddress\":\"21 2nd Street\",\"postalCode\":10021,\"state\":\"NY\",\"city\":\"New York\"},\"age\":25,\"firstName\":\"John\"}"; check("ret1", json); check("ret2", "{\"name\":\"Renektor\"}"); check("ret3", "{}"); check("ret4", "{\"address\":\"\"}"); check("ret5", "{\"age\":32}"); check("ret6", "{\"b\":\"\"}"); check("ret7", "{\"char\":{\"name\":\"Anivia\",\"lane\":\"mid\"}}"); check("ret8", "{\"#\":\"/\"}"); } public void test_convertlib_xml2json_expect_error(){ try { doCompile("function integer transform(){string json = xml2json(null); return 0;}","test_convertlib_xml2json_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string json = xml2json('<></>'); return 0;}","test_convertlib_xml2json_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string json = xml2json('<#>/</>'); return 0;}","test_convertlib_xml2json_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_cache() { // set default locale to en.US so the date is formatted uniformly on all systems Locale.setDefault(Locale.US); doCompile("test_convertlib_cache"); Calendar cal = Calendar.getInstance(); cal.set(2000, 6, 20, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Date checkDate = cal.getTime(); final SimpleDateFormat format = new SimpleDateFormat(); format.applyPattern("yyyy MMM dd"); check("sdate1", format.format(new Date())); check("sdate2", format.format(new Date())); check("date01", checkDate); check("date02", checkDate); check("date03", checkDate); check("date04", checkDate); check("date11", checkDate); check("date12", checkDate); check("date13", checkDate); } public void test_convertlib_base64byte() { doCompile("test_convertlib_base64byte"); assertTrue(Arrays.equals((byte[])getVariable("base64input"), Base64.decode("The quick brown fox jumps over the lazy dog"))); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_bits2str() { doCompile("test_convertlib_bits2str"); check("bitsAsString1", "00000000"); check("bitsAsString2", "11111111"); check("bitsAsString3", "010100000100110110100000"); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_bool2num() { doCompile("test_convertlib_bool2num"); check("resultTrue", 1); check("resultFalse", 0); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_byte2base64() throws UnsupportedEncodingException { doCompile("test_convertlib_byte2base64"); check("inputBase64", Base64.encodeBytes("Abeceda zedla deda".getBytes())); String longText = (String) getVariable("longText"); byte[] longTextBytes = longText.getBytes("UTF-8"); String inputBase64wrapped = Base64.encodeBytes(longTextBytes, Base64.NO_OPTIONS); String inputBase64nowrap = Base64.encodeBytes(longTextBytes, Base64.DONT_BREAK_LINES); check("inputBase64wrapped", inputBase64wrapped); assertTrue(((String) getVariable("inputBase64wrapped")).indexOf('\n') >= 0); check("inputBase64nowrap", inputBase64nowrap); assertTrue(((String) getVariable("inputBase64nowrap")).indexOf('\n') < 0); check("nullLiteralOutput", null); check("nullVariableOutput", null); check("nullLiteralOutputWrapped", null); check("nullVariableOutputWrapped", null); check("nullLiteralOutputNowrap", null); check("nullVariableOutputNowrap", null); } public void test_convertlib_byte2base64_expect_error(){ try { doCompile("function integer transform(){boolean b = null; string s = byte2base64(str2byte('Rengar', 'utf-8'), b);return 0;}","test_convertlib_byte2base64_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = byte2base64(str2byte('Rengar', 'utf-8'), null);return 0;}","test_convertlib_byte2base64_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_byte2hex() { doCompile("test_convertlib_byte2hex"); check("hexResult", "41626563656461207a65646c612064656461"); check("test_null1", null); check("test_null2", null); } public void test_convertlib_date2long() { doCompile("test_convertlib_date2long"); check("bornDate", BORN_MILLISEC_VALUE); check("zeroDate", 0l); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_date2num() { doCompile("test_convertlib_date2num"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); check("yearDate", 1987); check("monthDate", 5); check("secondDate", 0); check("yearBorn", cal.get(Calendar.YEAR)); check("monthBorn", cal.get(Calendar.MONTH) + 1); //Calendar enumerates months from 0, not 1; check("secondBorn", cal.get(Calendar.SECOND)); check("yearMin", 1970); check("monthMin", 1); check("weekMin", 1); check("weekMinCs", 1); check("dayMin", 1); check("hourMin", 1); //TODO: check! check("minuteMin", 0); check("secondMin", 0); check("millisecMin", 0); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_date2num_expect_error(){ try { doCompile("function integer transform(){number num = date2num(1982-09-02,null); return 0;}","test_convertlib_date2num_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){number num = date2num(1982-09-02,null,null); return 0;}","test_convertlib_date2num_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string s = null; number num = date2num(1982-09-02,null,s); return 0;}","test_convertlib_date2num_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string s = null; number num = date2num(1982-09-02,year,s); return 0;}","test_convertlib_date2num_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_convertlib_date2str() { doCompile("test_convertlib_date2str"); check("inputDate", "1987:05:12"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd"); check("bornDate", sdf.format(BORN_VALUE)); SimpleDateFormat sdfCZ = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("cs.CZ")); check("czechBornDate", sdfCZ.format(BORN_VALUE)); SimpleDateFormat sdfEN = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("en")); check("englishBornDate", sdfEN.format(BORN_VALUE)); { String[] locales = {"en", "pl", null, "cs.CZ", null}; List<String> expectedDates = new ArrayList<String>(); for (String locale: locales) { expectedDates.add(new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale(locale)).format(BORN_VALUE)); } check("loopTest", expectedDates); } SimpleDateFormat sdfGMT8 = new SimpleDateFormat("yyyy:MMMM:dd z", MiscUtils.createLocale("en")); sdfGMT8.setTimeZone(TimeZone.getTimeZone("GMT+8")); check("timeZone", sdfGMT8.format(BORN_VALUE)); check("nullRet", null); check("nullRet2", null); check("nullRet3", "2011-04-15"); check("nullRet4", "2011-04-15"); check("nullRet5", "2011-04-15"); } public void test_convertlib_date2str_expect_error(){ try { doCompile("function integer transform(){string str = date2str(2001-12-15, 'xxx.MM.dd'); printErr(str); return 0;}","test_convertlib_date2str_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_decimal2double() { doCompile("test_convertlib_decimal2double"); check("toDouble", 0.007d); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_decimal2double_expect_error(){ try { String str ="function integer transform(){" + "decimal dec = str2decimal('9"+ Double.MAX_VALUE +"');" + "double dou = decimal2double(dec);" + "return 0;}" ; doCompile(str,"test_convertlib_decimal2double_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_decimal2integer() { doCompile("test_convertlib_decimal2integer"); check("toInteger", 0); check("toInteger2", -500); check("toInteger3", 1000000); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_decimal2integer_expect_error(){ try { doCompile("function integer transform(){integer int = decimal2integer(352147483647.23);return 0;}","test_convertlib_decimal2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_decimal2long() { doCompile("test_convertlib_decimal2long"); check("toLong", 0l); check("toLong2", -500l); check("toLong3", 10000000000l); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_decimal2long_expect_error(){ try { doCompile("function integer transform(){long l = decimal2long(9759223372036854775807.25); return 0;}","test_convertlib_decimal2long_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_double2integer() { doCompile("test_convertlib_double2integer"); check("toInteger", 0); check("toInteger2", -500); check("toInteger3", 1000000); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_double2integer_expect_error(){ try { doCompile("function integer transform(){integer int = double2integer(352147483647.1); return 0;}","test_convertlib_double2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_double2long() { doCompile("test_convertlib_double2long"); check("toLong", 0l); check("toLong2", -500l); check("toLong3", 10000000000l); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_double2long_expect_error(){ try { doCompile("function integer transform(){long l = double2long(1.3759739E23); return 0;}","test_convertlib_double2long_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_getFieldName() { doCompile("test_convertlib_getFieldName"); check("fieldNames",Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency")); } public void test_convertlib_getFieldType() { doCompile("test_convertlib_getFieldType"); check("fieldTypes",Arrays.asList(DataFieldType.STRING.getName(), DataFieldType.NUMBER.getName(), DataFieldType.STRING.getName(), DataFieldType.DATE.getName(), DataFieldType.LONG.getName(), DataFieldType.INTEGER.getName(), DataFieldType.BOOLEAN.getName(), DataFieldType.BYTE.getName(), DataFieldType.DECIMAL.getName())); } public void test_convertlib_hex2byte() { doCompile("test_convertlib_hex2byte"); assertTrue(Arrays.equals((byte[])getVariable("fromHex"), BYTEARRAY_VALUE)); check("test_null", null); } public void test_convertlib_long2date() { doCompile("test_convertlib_long2date"); check("fromLong1", new Date(0)); check("fromLong2", new Date(50000000000L)); check("fromLong3", new Date(-5000L)); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_long2integer() { doCompile("test_convertlib_long2integer"); check("fromLong1", 10); check("fromLong2", -10); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_long2integer_expect_error(){ //this test should be expected to success in future try { doCompile("function integer transform(){integer i = long2integer(200032132463123L); return 0;}","test_convertlib_long2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_long2packDecimal() { doCompile("test_convertlib_long2packDecimal"); assertTrue(Arrays.equals((byte[])getVariable("packedLong"), new byte[] {5, 0, 12})); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_md5() { doCompile("test_convertlib_md5"); assertTrue(Arrays.equals((byte[])getVariable("md5Hash1"), Digest.digest(DigestType.MD5, "The quick brown fox jumps over the lazy dog"))); assertTrue(Arrays.equals((byte[])getVariable("md5Hash2"), Digest.digest(DigestType.MD5, BYTEARRAY_VALUE))); assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.MD5, ""))); } public void test_convertlib_md5_expect_error(){ //CLO-1254 try { doCompile("function integer transform(){string s = null; byte b = md5(s); return 0;}","test_convertlib_md5_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte s = null; byte b = md5(s); return 0;}","test_convertlib_md5_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_num2bool() { doCompile("test_convertlib_num2bool"); check("integerTrue", true); check("integerFalse", false); check("longTrue", true); check("longFalse", false); check("doubleTrue", true); check("doubleFalse", false); check("decimalTrue", true); check("decimalFalse", false); check("nullInt", null); check("nullLong", null); check("nullDouble", null); check("nullDecimal", null); } public void test_convertlib_num2str() { System.out.println("num2str() test:"); doCompile("test_convertlib_num2str"); check("intOutput", Arrays.asList("16", "10000", "20", "10", "1.235E3", "12 350 001 Kcs")); check("longOutput", Arrays.asList("16", "10000", "20", "10", "1.235E13", "12 350 001 Kcs")); check("doubleOutput", Arrays.asList("16.16", "0x1.028f5c28f5c29p4", "1.23548E3", "12 350 001,1 Kcs")); check("decimalOutput", Arrays.asList("16.16", "1235.44", "12 350 001,1 Kcs")); check("nullIntRet", Arrays.asList(null,null,null,null,"12","12",null,null)); check("nullLongRet", Arrays.asList(null,null,null,null,"12","12",null,null)); check("nullDoubleRet", Arrays.asList(null,null,null,null,"12.2","12.2",null,null)); check("nullDecRet", Arrays.asList(null,null,null,"12.2","12.2",null,null)); } public void test_convertlib_num2str_expect_error(){ try { doCompile("function integer transform(){integer var = null; string ret = num2str(12, var); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer var = null; string ret = num2str(12L, var); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer var = null; string ret = num2str(12.3, var); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string ret = num2str(12.3, 2); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string ret = num2str(12.3, 8); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_packdecimal2long() { doCompile("test_convertlib_packDecimal2long"); check("unpackedLong", PackedDecimal.parse(BYTEARRAY_VALUE)); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_sha() { doCompile("test_convertlib_sha"); assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA, "The quick brown fox jumps over the lazy dog"))); assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA, BYTEARRAY_VALUE))); assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.SHA, ""))); } public void test_convertlib_sha_expect_error(){ // CLO-1258 try { doCompile("function integer transform(){string s = null; byte b = sha(s); return 0;}","test_convertlib_sha_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte s = null; byte b = sha(s); return 0;}","test_convertlib_sha_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_sha256() { doCompile("test_convertlib_sha256"); assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA256, "The quick brown fox jumps over the lazy dog"))); assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA256, BYTEARRAY_VALUE))); assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.SHA256, ""))); } public void test_convertlib_sha256_expect_error(){ // CLO-1258 try { doCompile("function integer transform(){string a = null; byte b = sha256(a); return 0;}","test_convertlib_sha256_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte a = null; byte b = sha256(a); return 0;}","test_convertlib_sha256_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2bits() { doCompile("test_convertlib_str2bits"); //TODO: uncomment -> test will pass, but is that correct? assertTrue(Arrays.equals((byte[]) getVariable("textAsBits1"), new byte[] {0/*, 0, 0, 0, 0, 0, 0, 0*/})); assertTrue(Arrays.equals((byte[]) getVariable("textAsBits2"), new byte[] {-1/*, 0, 0, 0, 0, 0, 0, 0*/})); assertTrue(Arrays.equals((byte[]) getVariable("textAsBits3"), new byte[] {10, -78, 5/*, 0, 0, 0, 0, 0*/})); assertTrue(Arrays.equals((byte[]) getVariable("test_empty"), new byte[] {})); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_str2bool() { doCompile("test_convertlib_str2bool"); check("fromTrueString", true); check("fromFalseString", false); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_str2bool_expect_error(){ try { doCompile("function integer transform(){boolean b = str2bool('asd'); return 0;}","test_convertlib_str2bool_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){boolean b = str2bool(''); return 0;}","test_convertlib_str2bool_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_convertlib_str2date() { doCompile("test_convertlib_str2date"); Calendar cal = Calendar.getInstance(); cal.set(2005,10,19,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("date1", cal.getTime()); cal.clear(); cal.set(2050, 4, 19, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Date checkDate = cal.getTime(); check("date2", checkDate); check("date3", checkDate); cal.clear(); cal.setTimeZone(TimeZone.getTimeZone("GMT+8")); cal.set(2013, 04, 30, 17, 15, 12); check("withTimeZone1", cal.getTime()); cal.clear(); cal.setTimeZone(TimeZone.getTimeZone("GMT-8")); cal.set(2013, 04, 30, 17, 15, 12); check("withTimeZone2", cal.getTime()); assertFalse(getVariable("withTimeZone1").equals(getVariable("withTimeZone2"))); check("nullRet1", null); check("nullRet2", null); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); } public void test_convertlib_str2date_expect_error(){ try { doCompile("function integer transform(){date d = str2date('1987-11-17', 'dd.MM.yyyy'); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('1987-33-17', 'yyyy-MM-dd'); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('17.11.1987', null, 'cs.CZ'); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('17.11.1987', 'yyyy-MM-dd', null); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('17.11.1987', 'yyyy-MM-dd', 'cs.CZ', null); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2decimal() { doCompile("test_convertlib_str2decimal"); check("parsedDecimal1", new BigDecimal("100.13")); check("parsedDecimal2", new BigDecimal("123123123.123")); check("parsedDecimal3", new BigDecimal("-350000.01")); check("parsedDecimal4", new BigDecimal("1000000")); check("parsedDecimal5", new BigDecimal("1000000.99")); check("parsedDecimal6", new BigDecimal("123123123.123")); check("parsedDecimal7", new BigDecimal("5.01")); check("nullRet1", null); check("nullRet2", null); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); check("nullRet7", new BigDecimal("5.05")); // CLO-1614 check("nullRet8", new BigDecimal("5.05")); check("nullRet9", new BigDecimal("5.05")); check("nullRet10", new BigDecimal("5.05")); check("nullRet11", new BigDecimal("5.05")); check("nullRet12", new BigDecimal("5.05")); check("nullRet13", new BigDecimal("5.05")); check("nullRet14", new BigDecimal("5.05")); check("nullRet15", new BigDecimal("5.05")); check("nullRet16", new BigDecimal("5.05")); } public void test_convertlib_str2decimal_expect_result(){ try { doCompile("function integer transform(){decimal d = str2decimal(''); return 0;}","test_convertlib_str2decimal_expect_result"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK','#.#CZ'); return 0;}","test_convertlib_str2decimal_expect_result"); fail(); } catch (Exception e) { // do nothing } // CLO-1614 try { doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK',null); return 0;}","test_convertlib_str2decimal_expect_result"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK',null, null); return 0;}","test_convertlib_str2decimal_expect_result"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2double() { doCompile("test_convertlib_str2double"); check("parsedDouble1", 100.13); check("parsedDouble2", 123123123.123); check("parsedDouble3", -350000.01); check("nullRet1", null); check("nullRet2", null); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); check("nullRet7", 12.34d); // CLO-1614 check("nullRet8", 12.34d); check("nullRet9", 12.34d); check("nullRet10", 12.34d); check("nullRet11", 12.34d); check("nullRet12", 12.34d); check("nullRet13", 12.34d); check("nullRet14", 12.34d); check("nullRet15", 12.34d); } public void test_convertlib_str2double_expect_error(){ try { doCompile("function integer transform(){double d = str2double(''); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double d = str2double('text'); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double d = str2double('0.90c','#.# c'); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } // CLO-1614 try { doCompile("function integer transform(){double d = str2double('0.90c',null); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double d = str2double('0.90c', null); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double d = str2double('0.90c', null, null); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2integer() { doCompile("test_convertlib_str2integer"); check("parsedInteger1", 123456789); check("parsedInteger2", 123123); check("parsedInteger3", -350000); check("parsedInteger4", 419); check("nullRet1", 123); check("nullRet2", 123); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); check("nullRet7", null); check("nullRet8", null); check("nullRet9", null); // CLO-1614 // check("nullRet10", 123); // ambiguous check("nullRet11", 123); check("nullRet12", 123); check("nullRet13", 123); check("nullRet14", 123); check("nullRet15", 123); check("nullRet16", 123); check("nullRet17", 123); } public void test_convertlib_str2integer_expect_error(){ try { doCompile("function integer transform(){integer i = str2integer('abc'); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = str2integer(''); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = str2integer('123 mil', '###mil'); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; integer i = str2integer('123,1', s); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; integer i = str2integer('123,1', s, null); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = str2integer('1F', 2); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2long() { doCompile("test_convertlib_str2long"); check("parsedLong1", 1234567890123L); check("parsedLong2", 123123123456789L); check("parsedLong3", -350000L); check("parsedLong4", 133L); check("nullRet1", 123l); check("nullRet2", 123l); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); check("nullRet7", null); check("nullRet8", null); check("nullRet9", null); // CLO-1614 // check("nullRet10", 123l); // ambiguous check("nullRet11", 123l); check("nullRet12", 123l); check("nullRet13", 123l); check("nullRet14", 123l); check("nullRet15", 123l); check("nullRet16", 123l); check("nullRet17", 123l); } public void test_convertlib_str2long_expect_error(){ try { doCompile("function integer transform(){long i = str2long('abc'); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long(''); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long('13', '## bls'); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long('13', '## bls' , null); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long('13 L', null, 'cs.Cz'); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long('1A', 2); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_toString() { doCompile("test_convertlib_toString"); check("integerString", "10"); check("longString", "110654321874"); check("doubleString", "1.547874E-14"); check("decimalString", "-6847521431.1545874"); check("listString", "[not ALI A, not ALI B, not ALI D..., but, ALI H!]"); check("mapString", "{1=Testing, 2=makes, 3=me, 4=crazy :-)}"); String byteMapString = getVariable("byteMapString").toString(); assertTrue(byteMapString.contains("1=value1")); assertTrue(byteMapString.contains("2=value2")); String fieldByteMapString = getVariable("fieldByteMapString").toString(); assertTrue(fieldByteMapString.contains("key1=value1")); assertTrue(fieldByteMapString.contains("key2=value2")); check("byteListString", "[firstElement, secondElement]"); check("fieldByteListString", "[firstElement, secondElement]"); // CLO-1262 check("test_null_l", "null"); check("test_null_dec", "null"); check("test_null_d", "null"); check("test_null_i", "null"); } public void test_convertlib_str2byte() { doCompile("test_convertlib_str2byte"); checkArray("utf8Hello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("utf8Horse", new byte[] { 80, -59, -103, -61, -83, 108, 105, -59, -95, 32, -59, -66, 108, 117, -59, -91, 111, 117, -60, -115, 107, -61, -67, 32, 107, -59, -81, -59, -120, 32, 112, -60, -101, 108, 32, -60, -113, -61, -95, 98, 108, 115, 107, -61, -87, 32, -61, -77, 100, 121 }); checkArray("utf8Math", new byte[] { -62, -67, 32, -30, -123, -109, 32, -62, -68, 32, -30, -123, -107, 32, -30, -123, -103, 32, -30, -123, -101, 32, -30, -123, -108, 32, -30, -123, -106, 32, -62, -66, 32, -30, -123, -105, 32, -30, -123, -100, 32, -30, -123, -104, 32, -30, -126, -84, 32, -62, -78, 32, -62, -77, 32, -30, -128, -96, 32, -61, -105, 32, -30, -122, -112, 32, -30, -122, -110, 32, -30, -122, -108, 32, -30, -121, -110, 32, -30, -128, -90, 32, -30, -128, -80, 32, -50, -111, 32, -50, -110, 32, -30, -128, -109, 32, -50, -109, 32, -50, -108, 32, -30, -126, -84, 32, -50, -107, 32, -50, -106, 32, -49, -128, 32, -49, -127, 32, -49, -126, 32, -49, -125, 32, -49, -124, 32, -49, -123, 32, -49, -122, 32, -49, -121, 32, -49, -120, 32, -49, -119 }); checkArray("utf16Hello", new byte[] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 }); checkArray("utf16Horse", new byte[] { -2, -1, 0, 80, 1, 89, 0, -19, 0, 108, 0, 105, 1, 97, 0, 32, 1, 126, 0, 108, 0, 117, 1, 101, 0, 111, 0, 117, 1, 13, 0, 107, 0, -3, 0, 32, 0, 107, 1, 111, 1, 72, 0, 32, 0, 112, 1, 27, 0, 108, 0, 32, 1, 15, 0, -31, 0, 98, 0, 108, 0, 115, 0, 107, 0, -23, 0, 32, 0, -13, 0, 100, 0, 121 }); checkArray("utf16Math", new byte[] { -2, -1, 0, -67, 0, 32, 33, 83, 0, 32, 0, -68, 0, 32, 33, 85, 0, 32, 33, 89, 0, 32, 33, 91, 0, 32, 33, 84, 0, 32, 33, 86, 0, 32, 0, -66, 0, 32, 33, 87, 0, 32, 33, 92, 0, 32, 33, 88, 0, 32, 32, -84, 0, 32, 0, -78, 0, 32, 0, -77, 0, 32, 32, 32, 0, 32, 0, -41, 0, 32, 33, -112, 0, 32, 33, -110, 0, 32, 33, -108, 0, 32, 33, -46, 0, 32, 32, 38, 0, 32, 32, 48, 0, 32, 3, -111, 0, 32, 3, -110, 0, 32, 32, 19, 0, 32, 3, -109, 0, 32, 3, -108, 0, 32, 32, -84, 0, 32, 3, -107, 0, 32, 3, -106, 0, 32, 3, -64, 0, 32, 3, -63, 0, 32, 3, -62, 0, 32, 3, -61, 0, 32, 3, -60, 0, 32, 3, -59, 0, 32, 3, -58, 0, 32, 3, -57, 0, 32, 3, -56, 0, 32, 3, -55 }); checkArray("macHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("macHorse", new byte[] { 80, -34, -110, 108, 105, -28, 32, -20, 108, 117, -23, 111, 117, -117, 107, -7, 32, 107, -13, -53, 32, 112, -98, 108, 32, -109, -121, 98, 108, 115, 107, -114, 32, -105, 100, 121 }); checkArray("asciiHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("isoHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("isoHorse", new byte[] { 80, -8, -19, 108, 105, -71, 32, -66, 108, 117, -69, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 }); checkArray("cpHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("cpHorse", new byte[] { 80, -8, -19, 108, 105, -102, 32, -98, 108, 117, -99, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 }); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_str2byte_expect_error(){ try { doCompile("function integer transform(){byte b = str2byte('wallace',null); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = str2byte('wallace','knock'); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = str2byte('wallace',null); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_byte2str() { doCompile("test_convertlib_byte2str"); String hello = "Hello World!"; String horse = "Příliš žluťoučký kůň pěl ďáblské ódy"; String math = "½ ⅓ ¼ ⅕ ⅙ ⅛ ⅔ ⅖ ¾ ⅗ ⅜ ⅘ € ² ³ † × ← → ↔ ⇒ … ‰ Α Β – Γ Δ € Ε Ζ π ρ ς σ τ υ φ χ ψ ω"; check("utf8Hello", hello); check("utf8Horse", horse); check("utf8Math", math); check("utf16Hello", hello); check("utf16Horse", horse); check("utf16Math", math); check("macHello", hello); check("macHorse", horse); check("asciiHello", hello); check("isoHello", hello); check("isoHorse", horse); check("cpHello", hello); check("cpHorse", horse); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_byte2str_expect_error(){ try { doCompile("function integer transform(){string s = byte2str(null,null); return 0;}","test_convertlib_byte2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = byte2str(str2byte('hello', 'utf-8'),null); return 0;}","test_convertlib_byte2str_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_conditional_fail() { doCompile("test_conditional_fail"); check("result", 3); } public void test_expression_statement(){ // test case for issue 4174 doCompileExpectErrors("test_expression_statement", Arrays.asList("Syntax error, statement expected","Syntax error, statement expected")); } public void test_dictionary_read() { doCompile("test_dictionary_read"); check("s", "Verdon"); check("i", Integer.valueOf(211)); check("l", Long.valueOf(226)); check("d", BigDecimal.valueOf(239483061)); check("n", Double.valueOf(934.2)); check("a", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime()); check("b", true); byte[] y = (byte[]) getVariable("y"); assertEquals(10, y.length); assertEquals(89, y[9]); check("sNull", null); check("iNull", null); check("lNull", null); check("dNull", null); check("nNull", null); check("aNull", null); check("bNull", null); check("yNull", null); check("stringList", Arrays.asList("aa", "bb", null, "cc")); check("dateList", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000))); @SuppressWarnings("unchecked") List<byte[]> byteList = (List<byte[]>) getVariable("byteList"); assertDeepEquals(byteList, Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78})); } public void test_dictionary_write() { doCompile("test_dictionary_write"); assertEquals(832, graph.getDictionary().getValue("i") ); assertEquals("Guil", graph.getDictionary().getValue("s")); assertEquals(Long.valueOf(540), graph.getDictionary().getValue("l")); assertEquals(BigDecimal.valueOf(621), graph.getDictionary().getValue("d")); assertEquals(934.2, graph.getDictionary().getValue("n")); assertEquals(new GregorianCalendar(1992, GregorianCalendar.DECEMBER, 2).getTime(), graph.getDictionary().getValue("a")); assertEquals(true, graph.getDictionary().getValue("b")); byte[] y = (byte[]) graph.getDictionary().getValue("y"); assertEquals(2, y.length); assertEquals(18, y[0]); assertEquals(-94, y[1]); assertEquals(Arrays.asList("xx", null), graph.getDictionary().getValue("stringList")); assertEquals(Arrays.asList(new Date(98000), null, new Date(76000)), graph.getDictionary().getValue("dateList")); @SuppressWarnings("unchecked") List<byte[]> byteList = (List<byte[]>) graph.getDictionary().getValue("byteList"); assertDeepEquals(byteList, Arrays.asList(null, new byte[] {(byte) 0xAB, (byte) 0xCD}, new byte[] {(byte) 0xEF})); check("assignmentReturnValue", "Guil"); } public void test_dictionary_write_null() { doCompile("test_dictionary_write_null"); assertEquals(null, graph.getDictionary().getValue("s")); assertEquals(null, graph.getDictionary().getValue("sVerdon")); assertEquals(null, graph.getDictionary().getValue("i") ); assertEquals(null, graph.getDictionary().getValue("i211") ); assertEquals(null, graph.getDictionary().getValue("l")); assertEquals(null, graph.getDictionary().getValue("l452")); assertEquals(null, graph.getDictionary().getValue("d")); assertEquals(null, graph.getDictionary().getValue("d621")); assertEquals(null, graph.getDictionary().getValue("n")); assertEquals(null, graph.getDictionary().getValue("n9342")); assertEquals(null, graph.getDictionary().getValue("a")); assertEquals(null, graph.getDictionary().getValue("a1992")); assertEquals(null, graph.getDictionary().getValue("b")); assertEquals(null, graph.getDictionary().getValue("bTrue")); assertEquals(null, graph.getDictionary().getValue("y")); assertEquals(null, graph.getDictionary().getValue("yFib")); } public void test_dictionary_invalid_key(){ doCompileExpectErrors("test_dictionary_invalid_key", Arrays.asList("Dictionary entry 'invalid' does not exist")); } public void test_dictionary_string_to_int(){ doCompileExpectErrors("test_dictionary_string_to_int", Arrays.asList("Type mismatch: cannot convert from 'string' to 'integer'","Type mismatch: cannot convert from 'string' to 'integer'")); } public void test_utillib_sleep() { long time = System.currentTimeMillis(); doCompile("test_utillib_sleep"); long tmp = System.currentTimeMillis() - time; assertTrue("sleep() function didn't pause execution "+ tmp, tmp >= 1000); } public void test_utillib_random_uuid() { doCompile("test_utillib_random_uuid"); assertNotNull(getVariable("uuid")); } public void test_stringlib_randomString(){ doCompile("string test; function integer transform(){test = randomString(1,3); return 0;}","test_stringlib_randomString"); assertNotNull(getVariable("test")); } public void test_stringlib_randomString_expect_error(){ try { doCompile("function integer transform(){randomString(-5, 1); return 0;}","test_stringlib_randomString_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){randomString(15, 2); return 0;}","test_stringlib_randomString_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_validUrl() { doCompile("test_stringlib_url"); check("urlValid", Arrays.asList(true, true, false, true, false, true)); check("protocol", Arrays.asList("http", "https", null, "sandbox", null, "zip")); check("userInfo", Arrays.asList("", "chuck:norris", null, "", null, "")); check("host", Arrays.asList("example.com", "server.javlin.eu", null, "cloveretl.test.scenarios", null, "")); check("port", Arrays.asList(-1, 12345, -2, -1, -2, -1)); check("path", Arrays.asList("", "/backdoor/trojan.cgi", null, "/graph/UDR_FileURL_SFTP_OneGzipFileSpecified.grf", null, "(sftp://test:test@koule/home/test/data-in/file2.zip)")); check("query", Arrays.asList("", "hash=SHA560;god=yes", null, "", null, "")); check("ref", Arrays.asList("", "autodestruct", null, "", null, "innerfolder2/URLIn21.txt")); } public void test_stringlib_escapeUrl() { doCompile("test_stringlib_escapeUrl"); check("escaped", "http://example.com/foo%20bar%5E"); check("unescaped", "http://example.com/foo bar^"); } public void test_stringlib_escapeUrl_unescapeUrl_expect_error(){ //test: escape - empty string try { doCompile("string test; function integer transform() {test = escapeUrl(''); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: escape - null string try { doCompile("string test; function integer transform() {test = escapeUrl(null); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: unescape - empty string try { doCompile("string test; function integer transform() {test = unescapeUrl(''); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: unescape - null try { doCompile("string test; function integer transform() {test = unescapeUrl(null); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: escape - invalid URL try { doCompile("string test; function integer transform() {test = escapeUrl('somewhere over the rainbow'); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: unescpae - invalid URL try { doCompile("string test; function integer transform() {test = unescapeUrl('mister%20postman'); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_resolveParams() { doCompile("test_stringlib_resolveParams"); check("resultNoParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in"); check("resultFalseFalseParams", "Special character representing new line is: \\n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in"); check("resultTrueFalseParams", "Special character representing new line is: \n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in"); check("resultFalseTrueParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in"); check("resultTrueTrueParams", "Special character representing new line is: \n calling CTL function MESSAGE; $DATAIN_DIR=./data-in"); } public void test_utillib_getEnvironmentVariables() { doCompile("test_utillib_getEnvironmentVariables"); check("empty", false); check("ret1", null); // CLO-1700 // check("ret2", null); // check("ret3", null); } public void test_utillib_getJavaProperties() { String key1 = "my.testing.property"; String key2 = "my.testing.property2"; String value = "my value"; String value2; assertNull(System.getProperty(key1)); assertNull(System.getProperty(key2)); System.setProperty(key1, value); try { doCompile("test_utillib_getJavaProperties"); value2 = System.getProperty(key2); } finally { System.clearProperty(key1); assertNull(System.getProperty(key1)); System.clearProperty(key2); assertNull(System.getProperty(key2)); } check("java_specification_name", "Java Platform API Specification"); check("my_testing_property", value); assertEquals("my value 2", value2); check("ret1", null); // CLO-1700 // check("ret2", null); // check("ret3", null); } public void test_utillib_getParamValues() { doCompile("test_utillib_getParamValues"); Map<String, String> params = new HashMap<String, String>(); params.put("PROJECT", "."); params.put("DATAIN_DIR", "./data-in"); params.put("COUNT", "3"); params.put("NEWLINE", "\\n"); // special characters should NOT be resolved check("params", params); check("ret1", null); check("ret2", null); check("ret3", null); } public void test_utillib_getParamValue() { doCompile("test_utillib_getParamValue"); Map<String, String> params = new HashMap<String, String>(); params.put("PROJECT", "."); params.put("DATAIN_DIR", "./data-in"); params.put("COUNT", "3"); params.put("NEWLINE", "\\n"); // special characters should NOT be resolved params.put("NONEXISTING", null); check("params", params); check("ret1", null); check("ret2", null); } public void test_stringlib_getUrlParts() { doCompile("test_stringlib_getUrlParts"); List<Boolean> isUrl = Arrays.asList(true, true, true, true, false); List<String> path = Arrays.asList( "/users/a6/15e83578ad5cba95c442273ea20bfa/msf-183/out5.txt", "/data-in/fileOperation/input.txt", "/data/file.txt", "/data/file.txt", null); List<String> protocol = Arrays.asList("sftp", "sandbox", "ftp", "https", null); List<String> host = Arrays.asList( "ava-fileManipulator1-devel.getgooddata.com", "cloveretl.test.scenarios", "ftp.test.com", "www.test.com", null); List<Integer> port = Arrays.asList(-1, -1, 21, 80, -2); List<String> userInfo = Arrays.asList( "user%40gooddata.com:password", "", "test:test", "test:test", null); List<String> ref = Arrays.asList("", "", "", "", null); List<String> query = Arrays.asList("", "", "", "", null); check("isUrl", isUrl); check("path", path); check("protocol", protocol); check("host", host); check("port", port); check("userInfo", userInfo); check("ref", ref); check("query", query); check("isURL_empty", false); check("path_empty", null); check("protocol_empty", null); check("host_empty", null); check("port_empty", -2); check("userInfo_empty", null); check("ref_empty", null); check("query_empty", null); check("isURL_null", false); check("path_null", null); check("protocol_null", null); check("host_null", null); check("port_null", -2); check("userInfo_null", null); check("ref_null", null); check("query_empty", null); } public void test_utillib_iif() throws UnsupportedEncodingException{ doCompile("test_utillib_iif"); check("ret1", "Renektor"); Calendar cal = Calendar.getInstance(); cal.set(2005,10,12,0,0,0); cal.set(Calendar.MILLISECOND,0); check("ret2", cal.getTime()); checkArray("ret3", "Akali".getBytes("UTF-8")); check("ret4", 236); check("ret5", 78L); check("ret6", 78.2d); check("ret7", new BigDecimal("87.69")); check("ret8", true); } public void test_utillib_iif_expect_error(){ try { doCompile("function integer transform(){boolean b = null; string str = iif(b, 'Rammus', 'Sion'); return 0;}","test_utillib_iif_expect_error"); fail(); } catch (Exception e) { // do nothing } //CLO-1701 try { doCompile("function integer transform(){string str = iif(null, 'Rammus', 'Sion'); return 0;}","test_utillib_iif_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_utillib_isnull(){ doCompile("test_utillib_isnull"); check("ret1", false); check("ret2", true); check("ret3", false); check("ret4", true); check("ret5", false); check("ret6", true); check("ret7", false); check("ret8", true); check("ret9", false); check("ret10", true); check("ret11", false); check("ret12", true); check("ret13", false); check("ret14", true); check("ret15", false); check("ret16", true); check("ret17", false); check("ret18", true); check("ret19", true); } public void test_utillib_nvl() throws UnsupportedEncodingException{ doCompile("test_utillib_nvl"); check("ret1", "Fiora"); check("ret2", "Olaf"); checkArray("ret3", "Elise".getBytes("UTF-8")); checkArray("ret4", "Diana".getBytes("UTF-8")); Calendar cal = Calendar.getInstance(); cal.set(2005,4,13,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret5", cal.getTime()); cal.clear(); cal.set(2004,2,14,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret6", cal.getTime()); check("ret7", 7); check("ret8", 8); check("ret9", 111l); check("ret10", 112l); check("ret11", 10.1d); check("ret12", 10.2d); check("ret13", new BigDecimal("12.2")); check("ret14", new BigDecimal("12.3")); check("ret15", null); } public void test_utillib_nvl2() throws UnsupportedEncodingException{ doCompile("test_utillib_nvl2"); check("ret1", "Ahri"); check("ret2", "Galio"); checkArray("ret3", "Mordekaiser".getBytes("UTF-8")); checkArray("ret4", "Zed".getBytes("UTF-8")); Calendar cal = Calendar.getInstance(); cal.set(2010,4,18,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret5", cal.getTime()); cal.clear(); cal.set(2008,7,9,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret6", cal.getTime()); check("ret7", 11); check("ret8", 18); check("ret9", 20L); check("ret10", 23L); check("ret11", 15.2d); check("ret12", 89.3d); check("ret13", new BigDecimal("22.2")); check("ret14", new BigDecimal("55.5")); check("ret15", null); check("ret16", null); check("ret17", "Shaco"); check("ret18", 12); check("ret19", 18.1d); check("ret20", 15L); check("ret21", new BigDecimal("18.1")); } public void test_utillib_toAbsolutePath(){ doCompile("test_utillib_toAbsolutePath"); assertNotNull(getVariable("ret1")); assertNotNull(getVariable("ret2")); check("ret3", null); } public void test_utillib_toAbsolutePath_expect_error(){ try { doCompile("function integer transform(){string str = toAbsolutePath(null); return 0;}","test_utillib_toAbsolutePath_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; string str = toAbsolutePath(s); return 0;}","test_utillib_toAbsolutePath_expect_error"); fail(); } catch (Exception e) { // do nothing } } }
UPDATE: test cases for CLO-1835 and CLO-1832 git-svn-id: 1b86a985b0847acdee38f4dd95cd5693fef2c0cb@15046 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
cloveretl.engine/test/org/jetel/ctl/CompilerTestCase.java
UPDATE: test cases for CLO-1835 and CLO-1832
<ide><path>loveretl.engine/test/org/jetel/ctl/CompilerTestCase.java <ide> // negative precision means the number of places after the decimal point <ide> // positive precision before the decimal point <ide> List<BigDecimal> expected = Arrays.asList( <del> new BigDecimal("1234567.1234567"), <add> new BigDecimal("0"), <add> new BigDecimal("1000000"), <add> new BigDecimal("1200000"), <add> new BigDecimal("1230000"), <add> new BigDecimal("1235000"), // rounded up <add> new BigDecimal("1234600"), // rounded up <add> new BigDecimal("1234570"), // rounded up <add> new BigDecimal("1234567"), <add> new BigDecimal("1234567.1"), <add> new BigDecimal("1234567.12"), <add> new BigDecimal("1234567.123"), <add> new BigDecimal("1234567.1235"), // rounded up <add> new BigDecimal("1234567.12346"), // rounded up <ide> new BigDecimal("1234567.123457"), // rounded up <del> new BigDecimal("1234567.12346"), // rounded up <del> new BigDecimal("1234567.1235"), // rounded up <del> new BigDecimal("1234567.123"), <del> new BigDecimal("1234567.12"), <del> new BigDecimal("1234567.1"), <del> new BigDecimal("1234567"), <del> new BigDecimal("1234570"), // rounded up <del> new BigDecimal("1234600"), // rounded up <del> new BigDecimal("1235000"), // rounded up <del> new BigDecimal("1230000"), <del> new BigDecimal("1200000"), <del> new BigDecimal("1000000"), <del> new BigDecimal("0") <add> new BigDecimal("1234567.1234567") <ide> ); <ide> //CLO-1835 <del>// compareDecimals(expected, (List<BigDecimal>) getVariable("decimal2Result")); <add> compareDecimals(expected, (List<BigDecimal>) getVariable("decimal2Result")); <ide> //CLO-1832 <del>// check("intWithPrecisionResult", 1200); <del>// check("longWithPrecisionResult", 123500L); <add> check("intWithPrecisionResult", 1234d); <add> check("longWithPrecisionResult", 123456d); <add> check("ret1", 1234d); <add> check("ret2", 13565d); <ide> } <ide> <ide> public void test_mathlib_round_expect_error(){
Java
mit
889a942c6dfbb7a0143ef064deacca32067bdd2b
0
ictrobot/Cubes,RedTroop/Cubes_2,RedTroop/Cubes_2,ictrobot/Cubes
package ethanjones.cubes.graphics.menu; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Array; import java.util.ArrayList; import java.util.List; import ethanjones.cubes.block.Block; import ethanjones.cubes.block.Blocks; import ethanjones.cubes.core.util.BlockFace; import ethanjones.cubes.graphics.world.BlockTextureHandler; public class MenuManager { private static Menu menu; private static Array<Menu> menus = new Array<Menu>(); private static TextureRegion texture; private static SpriteBatch spriteBatch; private static boolean disableBackground = false; public static void setMenu(Menu menu) { int i = menus.indexOf(menu, true); if (i == -1) { menus.add(menu); } else if (i + 1 < menus.size) { menus.removeRange(i + 1, menus.size - 1); } MenuManager.menu = menu; } public static Menu getPrevious(Menu menu) { int index = menus.indexOf(menu, true); if (index == -1 || index == 0) return null; return menus.get(index - 1); } public static void renderBackground() { if (disableBackground) return; if (texture == null) { List<Block> blocks = new ArrayList<Block>(); blocks.addAll(Blocks.getBlocks()); while (texture == null && blocks.size() > 0) { int index = MathUtils.random(0, blocks.size() - 1); Block block = blocks.get(index); BlockTextureHandler textureHandler; try { textureHandler = block.getTextureHandler(null); if (textureHandler == null) throw new NullPointerException(); } catch (Exception e) { blocks.remove(index); continue; } texture = textureHandler.getSide(BlockFace.posX).textureRegion; } if (texture == null) { disableBackground = true; return; } } if (spriteBatch == null) { spriteBatch = new SpriteBatch(); } spriteBatch.begin(); int width = texture.getRegionWidth(); int height = texture.getRegionHeight(); int xTimes = (int) Math.floor((float) Gdx.graphics.getWidth() / width); int yTimes = (int) Math.floor((float) Gdx.graphics.getHeight() / height); for (int x = 0; x <= xTimes; x++) { for (int y = 0; y <= yTimes; y++) { spriteBatch.draw(texture, x * width, y * height, width, height); } } spriteBatch.end(); } }
core/src/ethanjones/cubes/graphics/menu/MenuManager.java
package ethanjones.cubes.graphics.menu; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Array; import java.util.List; import ethanjones.cubes.block.Block; import ethanjones.cubes.block.Blocks; import ethanjones.cubes.core.util.BlockFace; public class MenuManager { private static Menu menu; private static Array<Menu> menus = new Array<Menu>(); private static TextureRegion texture; private static SpriteBatch spriteBatch; public static void setMenu(Menu menu) { int i = menus.indexOf(menu, true); if (i == -1) { menus.add(menu); } else if (i + 1 < menus.size) { menus.removeRange(i + 1, menus.size - 1); } MenuManager.menu = menu; } public static Menu getPrevious(Menu menu) { int index = menus.indexOf(menu, true); if (index == -1 || index == 0) return null; return menus.get(index - 1); } public static void renderBackground() { if (texture == null) { List<Block> blocks = Blocks.getBlocks(); Block block = blocks.get(MathUtils.random(0, blocks.size() - 1)); texture = block.getTextureHandler(null).getSide(BlockFace.posX).textureRegion; } if (spriteBatch == null) { spriteBatch = new SpriteBatch(); } spriteBatch.begin(); int width = texture.getRegionWidth(); int height = texture.getRegionHeight(); int xTimes = (int) Math.floor((float) Gdx.graphics.getWidth() / width); int yTimes = (int) Math.floor((float) Gdx.graphics.getHeight() / height); for (int x = 0; x <= xTimes; x++) { for (int y = 0; y <= yTimes; y++) { spriteBatch.draw(texture, x * width, y * height, width, height); } } spriteBatch.end(); } }
Better random block selector for menu background
core/src/ethanjones/cubes/graphics/menu/MenuManager.java
Better random block selector for menu background
<ide><path>ore/src/ethanjones/cubes/graphics/menu/MenuManager.java <ide> import com.badlogic.gdx.graphics.g2d.TextureRegion; <ide> import com.badlogic.gdx.math.MathUtils; <ide> import com.badlogic.gdx.utils.Array; <add>import java.util.ArrayList; <ide> import java.util.List; <ide> <ide> import ethanjones.cubes.block.Block; <ide> import ethanjones.cubes.block.Blocks; <ide> import ethanjones.cubes.core.util.BlockFace; <add>import ethanjones.cubes.graphics.world.BlockTextureHandler; <ide> <ide> public class MenuManager { <ide> <ide> private static Array<Menu> menus = new Array<Menu>(); <ide> private static TextureRegion texture; <ide> private static SpriteBatch spriteBatch; <add> private static boolean disableBackground = false; <ide> <ide> public static void setMenu(Menu menu) { <ide> int i = menus.indexOf(menu, true); <ide> } <ide> <ide> public static void renderBackground() { <add> if (disableBackground) return; <ide> if (texture == null) { <del> List<Block> blocks = Blocks.getBlocks(); <del> Block block = blocks.get(MathUtils.random(0, blocks.size() - 1)); <del> texture = block.getTextureHandler(null).getSide(BlockFace.posX).textureRegion; <add> List<Block> blocks = new ArrayList<Block>(); <add> blocks.addAll(Blocks.getBlocks()); <add> while (texture == null && blocks.size() > 0) { <add> int index = MathUtils.random(0, blocks.size() - 1); <add> Block block = blocks.get(index); <add> BlockTextureHandler textureHandler; <add> try { <add> textureHandler = block.getTextureHandler(null); <add> if (textureHandler == null) throw new NullPointerException(); <add> } catch (Exception e) { <add> blocks.remove(index); <add> continue; <add> } <add> texture = textureHandler.getSide(BlockFace.posX).textureRegion; <add> } <add> if (texture == null) { <add> disableBackground = true; <add> return; <add> } <ide> } <ide> if (spriteBatch == null) { <ide> spriteBatch = new SpriteBatch();
JavaScript
mit
d8322f18e90a8ef5c7de350db6763b1d62467c7f
0
phetsims/dot,phetsims/dot,phetsims/dot
// Copyright 2013-2015, University of Colorado Boulder /** * An immutable permutation that can permute an array * * @author Jonathan Olson <[email protected]> */ define( function( require ) { 'use strict'; var dot = require( 'DOT/dot' ); var isArray = require( 'PHET_CORE/isArray' ); require( 'DOT/Util' ); // for rangeInclusive // Creates a permutation that will rearrange a list so that newList[i] = oldList[permutation[i]] var Permutation = dot.Permutation = function Permutation( indices ) { this.indices = indices; }; // An identity permutation with a specific number of elements Permutation.identity = function( size ) { assert && assert( size >= 0 ); var indices = new Array( size ); for ( var i = 0; i < size; i++ ) { indices[ i ] = i; } return new Permutation( indices ); }; // lists all permutations that have a given size Permutation.permutations = function( size ) { var result = []; Permutation.forEachPermutation( dot.rangeInclusive( 0, size - 1 ), function( integers ) { result.push( new Permutation( integers ) ); } ); return result; }; /** * Call our function with each permutation of the provided list PREFIXED by prefix, in lexicographic order * * @param array List to generate permutations of * @param prefix Elements that should be inserted at the front of each list before each call * @param callback Function to call */ function recursiveForEachPermutation( array, prefix, callback ) { if ( array.length === 0 ) { callback( prefix ); } else { for ( var i = 0; i < array.length; i++ ) { var element = array[ i ]; // remove the element from the array var nextArray = array.slice( 0 ); nextArray.splice( i, 1 ); // add it into the prefix var nextPrefix = prefix.slice( 0 ); nextPrefix.push( element ); recursiveForEachPermutation( nextArray, nextPrefix, callback ); } } } Permutation.forEachPermutation = function( array, callback ) { recursiveForEachPermutation( array, [], callback ); }; Permutation.prototype = { constructor: Permutation, size: function() { return this.indices.length; }, apply: function( arrayOrInt ) { if ( isArray( arrayOrInt ) ) { if ( arrayOrInt.length !== this.size() ) { throw new Error( 'Permutation length ' + this.size() + ' not equal to list length ' + arrayOrInt.length ); } // permute it as an array var result = new Array( arrayOrInt.length ); for ( var i = 0; i < arrayOrInt.length; i++ ) { result[ i ] = arrayOrInt[ this.indices[ i ] ]; } return result; } else { // permute a single index return this.indices[ arrayOrInt ]; } }, // The inverse of this permutation inverted: function() { var newPermutation = new Array( this.size() ); for ( var i = 0; i < this.size(); i++ ) { newPermutation[ this.indices[ i ] ] = i; } return new Permutation( newPermutation ); }, withIndicesPermuted: function( indices ) { var result = []; var that = this; Permutation.forEachPermutation( indices, function( integers ) { var oldIndices = that.indices; var newPermutation = oldIndices.slice( 0 ); for ( var i = 0; i < indices.length; i++ ) { newPermutation[ indices[ i ] ] = oldIndices[ integers[ i ] ]; } result.push( new Permutation( newPermutation ) ); } ); return result; }, toString: function() { return 'P[' + this.indices.join( ', ' ) + ']'; } }; Permutation.testMe = function( console ) { var a = new Permutation( [ 1, 4, 3, 2, 0 ] ); console.log( a.toString() ); var b = a.inverted(); console.log( b.toString() ); console.log( b.withIndicesPermuted( [ 0, 3, 4 ] ).toString() ); console.log( Permutation.permutations( 4 ).toString() ); }; return Permutation; } );
js/Permutation.js
// Copyright 2013-2015, University of Colorado Boulder /** * An immutable permutation that can permute an array * * @author Jonathan Olson <[email protected]> */ define( function( require ) { 'use strict'; var dot = require( 'DOT/dot' ); var isArray = require( 'PHET_CORE/isArray' ); require( 'DOT/Util' ); // for rangeInclusive // Creates a permutation that will rearrange a list so that newList[i] = oldList[permutation[i]] var Permutation = dot.Permutation = function Permutation( indices ) { this.indices = indices; }; // An identity permutation with a specific number of elements Permutation.identity = function( size ) { assert && assert( size >= 0 ); var indices = new Array( size ); for ( var i = 0; i < size; i++ ) { indices[ i ] = i; } return new Permutation( indices ); }; // lists all permutations that have a given size Permutation.permutations = function( size ) { var result = []; Permutation.forEachPermutation( dot.rangeInclusive( 0, size - 1 ), function( integers ) { result.push( new Permutation( integers ) ); } ); return result; }; /** * Call our function with each permutation of the provided list PREFIXED by prefix, in lexicographic order * * @param array List to generate permutations of * @param prefix Elements that should be inserted at the front of each list before each call * @param callback Function to call */ function recursiveForEachPermutation( array, prefix, callback ) { if ( array.length === 0 ) { callback.call( undefined, prefix ); } else { for ( var i = 0; i < array.length; i++ ) { var element = array[ i ]; // remove the element from the array var nextArray = array.slice( 0 ); nextArray.splice( i, 1 ); // add it into the prefix var nextPrefix = prefix.slice( 0 ); nextPrefix.push( element ); recursiveForEachPermutation( nextArray, nextPrefix, callback ); } } } Permutation.forEachPermutation = function( array, callback ) { recursiveForEachPermutation( array, [], callback ); }; Permutation.prototype = { constructor: Permutation, size: function() { return this.indices.length; }, apply: function( arrayOrInt ) { if ( isArray( arrayOrInt ) ) { if ( arrayOrInt.length !== this.size() ) { throw new Error( 'Permutation length ' + this.size() + ' not equal to list length ' + arrayOrInt.length ); } // permute it as an array var result = new Array( arrayOrInt.length ); for ( var i = 0; i < arrayOrInt.length; i++ ) { result[ i ] = arrayOrInt[ this.indices[ i ] ]; } return result; } else { // permute a single index return this.indices[ arrayOrInt ]; } }, // The inverse of this permutation inverted: function() { var newPermutation = new Array( this.size() ); for ( var i = 0; i < this.size(); i++ ) { newPermutation[ this.indices[ i ] ] = i; } return new Permutation( newPermutation ); }, withIndicesPermuted: function( indices ) { var result = []; var that = this; Permutation.forEachPermutation( indices, function( integers ) { var oldIndices = that.indices; var newPermutation = oldIndices.slice( 0 ); for ( var i = 0; i < indices.length; i++ ) { newPermutation[ indices[ i ] ] = oldIndices[ integers[ i ] ]; } result.push( new Permutation( newPermutation ) ); } ); return result; }, toString: function() { return 'P[' + this.indices.join( ', ' ) + ']'; } }; Permutation.testMe = function( console ) { var a = new Permutation( [ 1, 4, 3, 2, 0 ] ); console.log( a.toString() ); var b = a.inverted(); console.log( b.toString() ); console.log( b.withIndicesPermuted( [ 0, 3, 4 ] ).toString() ); console.log( Permutation.permutations( 4 ).toString() ); }; return Permutation; } );
Removing useless call(), see https://github.com/phetsims/scenery-phet/issues/193
js/Permutation.js
Removing useless call(), see https://github.com/phetsims/scenery-phet/issues/193
<ide><path>s/Permutation.js <ide> */ <ide> function recursiveForEachPermutation( array, prefix, callback ) { <ide> if ( array.length === 0 ) { <del> callback.call( undefined, prefix ); <add> callback( prefix ); <ide> } <ide> else { <ide> for ( var i = 0; i < array.length; i++ ) {
Java
apache-2.0
5124f64f686eb74b84ce3ea1fd3fd502242391f7
0
OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine
package org.ovirt.engine.core.bll.storage.pool; import java.util.Collections; import java.util.List; import java.util.Map; import org.ovirt.engine.core.bll.Backend; import org.ovirt.engine.core.bll.LockMessagesMatchUtil; import org.ovirt.engine.core.bll.NonTransactiveCommandAttribute; import org.ovirt.engine.core.bll.context.CommandContext; import org.ovirt.engine.core.bll.storage.connection.StorageHelperDirector; import org.ovirt.engine.core.bll.validator.storage.StorageDomainToPoolRelationValidator; import org.ovirt.engine.core.bll.validator.storage.StorageDomainValidator; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.action.LockProperties; import org.ovirt.engine.core.common.action.LockProperties.Scope; import org.ovirt.engine.core.common.action.StorageDomainPoolParametersBase; import org.ovirt.engine.core.common.action.StoragePoolWithStoragesParameter; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.businessentities.OvfEntityData; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.StorageDomainStatic; import org.ovirt.engine.core.common.businessentities.StorageDomainStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.StorageFormatType; import org.ovirt.engine.core.common.businessentities.StoragePool; import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMap; import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMapId; import org.ovirt.engine.core.common.businessentities.StoragePoolStatus; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.errors.EngineError; import org.ovirt.engine.core.common.errors.EngineException; import org.ovirt.engine.core.common.errors.EngineMessage; import org.ovirt.engine.core.common.locks.LockingGroup; import org.ovirt.engine.core.common.queries.StorageDomainsAndStoragePoolIdQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.utils.VersionStorageFormatUtil; import org.ovirt.engine.core.common.vdscommands.CreateStoragePoolVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.TransactionScopeOption; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; @NonTransactiveCommandAttribute(forceCompensation = true) public class AddStoragePoolWithStoragesCommand<T extends StoragePoolWithStoragesParameter> extends UpdateStoragePoolCommand<T> { public AddStoragePoolWithStoragesCommand(T parameters) { this(parameters, null); } public AddStoragePoolWithStoragesCommand(T parameters, CommandContext commandContext) { super(parameters, commandContext); } /** * Constructor for command creation when compensation is applied on startup * * @param commandId */ protected AddStoragePoolWithStoragesCommand(Guid commandId) { super(commandId); } @Override protected LockProperties applyLockProperties(LockProperties lockProperties) { return lockProperties.withScope(Scope.Execution); } private StorageDomain masterStorageDomain = null; VDSReturnValue retVal; @Override protected void executeCommand() { if (updateStorageDomainsInDb()) { // setting storage pool status to maintenance StoragePool storagePool = getStoragePool(); getCompensationContext().snapshotEntity(storagePool); TransactionSupport.executeInNewTransaction(new TransactionMethod<Object>() { @Override public Object runInTransaction() { getStoragePool().setStatus(StoragePoolStatus.Maintenance); getStoragePool().setStoragePoolFormatType(masterStorageDomain.getStorageFormat()); DbFacade.getInstance().getStoragePoolDao().update(getStoragePool()); getCompensationContext().stateChanged(); StoragePoolStatusHandler.poolStatusChanged(getStoragePool().getId(), getStoragePool().getStatus()); return null; } }); // Following code performs only read operations, therefore no need for new transaction boolean result = false; retVal = null; for (VDS vds : getAllRunningVdssInPool()) { setVds(vds); for (Guid storageDomainId : getParameters().getStorages()) { // now the domain should have the mapping // with the pool in db StorageDomain storageDomain = DbFacade.getInstance() .getStorageDomainDao() .getForStoragePool(storageDomainId, getStoragePool().getId()); StorageHelperDirector.getInstance() .getItem(storageDomain.getStorageType()) .connectStorageToDomainByVdsId(storageDomain, getVds().getId()); } retVal = addStoragePoolInIrs(); if (!retVal.getSucceeded() && retVal.getVdsError().getCode() == EngineError.StorageDomainAccessError) { log.warn("Error creating storage pool on vds '{}' - continuing", vds.getName()); continue; } else { // storage pool creation succeeded or failed // but didn't throw exception result = retVal.getSucceeded(); break; } } setSucceeded(result); if (!result) { if (retVal != null && retVal.getVdsError().getCode() != null) { throw new EngineException(retVal.getVdsError().getCode(), retVal.getVdsError().getMessage()); } else { // throw exception to cause rollback and stop the // command throw new EngineException(EngineError.ENGINE_ERROR_CREATING_STORAGE_POOL); } } else { registerOvfStoreDisks(); } } // Create pool phase completed, no rollback is needed here, so compensation information needs to be cleared! TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().resetCompensation(); return null; } }); freeLock(); // if create succeeded activate if (getSucceeded()) { activateStorageDomains(); } } private boolean updateStorageDomainsInDb() { boolean result = TransactionSupport.executeInNewTransaction(new TransactionMethod<Boolean>() { @Override public Boolean runInTransaction() { for (Guid storageDomainId : getParameters().getStorages()) { StorageDomain storageDomain = DbFacade.getInstance().getStorageDomainDao().get( storageDomainId); if (storageDomain != null) { StoragePoolIsoMap mapFromDB = DbFacade.getInstance() .getStoragePoolIsoMapDao() .get(new StoragePoolIsoMapId(storageDomain.getId(), getStoragePool().getId())); boolean existingInDb = mapFromDB != null; if (existingInDb) { getCompensationContext().snapshotEntity(mapFromDB); } final StorageDomainStatic staticDomain = storageDomain.getStorageStaticData(); boolean staticDomainChanged = false; StorageFormatType requiredFormatType = VersionStorageFormatUtil.getRequiredForVersion (getStoragePool().getCompatibilityVersion(), storageDomain.getStorageType()); if (staticDomain.getStorageFormat().compareTo(requiredFormatType) < 0) { if (!staticDomainChanged) { getCompensationContext().snapshotEntity(staticDomain); } staticDomain.setStorageFormat(requiredFormatType); staticDomainChanged = true; } storageDomain.setStoragePoolId(getStoragePool().getId()); if (masterStorageDomain == null && storageDomain.getStorageDomainType() == StorageDomainType.Data) { if (!staticDomainChanged) { getCompensationContext().snapshotEntity(staticDomain); } storageDomain.setStorageDomainType(StorageDomainType.Master); staticDomainChanged = true; masterStorageDomain = storageDomain; // The update of storage pool should be without compensation, // this is why we run it in a different SUPRESS transaction. updateStoragePoolMasterDomainVersionInDiffTransaction(); } if (staticDomainChanged) { getStorageDomainStaticDao().update(staticDomain); } storageDomain.setStatus(StorageDomainStatus.Locked); if (existingInDb) { DbFacade.getInstance() .getStoragePoolIsoMapDao() .update(storageDomain.getStoragePoolIsoMapData()); } else { DbFacade.getInstance() .getStoragePoolIsoMapDao() .save(storageDomain.getStoragePoolIsoMapData()); getCompensationContext().snapshotNewEntity(storageDomain.getStoragePoolIsoMapData()); } } else { return false; } } getCompensationContext().stateChanged(); return true; } }); return result && masterStorageDomain != null; } /** * Save the master version out of the transaction */ private VDSReturnValue addStoragePoolInIrs() { return runVdsCommand(VDSCommandType.CreateStoragePool, new CreateStoragePoolVDSCommandParameters(getVds().getId(), getStoragePool().getId(), getStoragePool().getName(), masterStorageDomain.getId(), getParameters().getStorages(), getStoragePool() .getMasterDomainVersion())); } private boolean activateStorageDomains() { boolean returnValue = true; for (final Guid storageDomainId : getParameters().getStorages()) { StorageDomainPoolParametersBase activateParameters = new StorageDomainPoolParametersBase(storageDomainId, getStoragePool().getId()); activateParameters.setSessionId(getParameters().getSessionId()); activateParameters.setTransactionScopeOption(TransactionScopeOption.RequiresNew); returnValue = Backend.getInstance() .runInternalAction(VdcActionType.ActivateStorageDomain, activateParameters).getSucceeded(); // if activate domain failed then set domain status to inactive if (!returnValue) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { DbFacade.getInstance() .getStoragePoolIsoMapDao() .updateStatus( new StoragePoolIsoMapId(storageDomainId, getStoragePool().getId()), StorageDomainStatus.Inactive); return null; } }); } } return returnValue; } private void registerOvfStoreDisks() { for (final Guid storageDomainId : getParameters().getStorages()) { resetOvfStoreDisks(); final List<OvfEntityData> unregisteredEntitiesFromOvfDisk = getEntitiesFromStorageOvfDisk(storageDomainId, getStoragePool().getId()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { List<DiskImage> ovfStoreDiskImages = getAllOVFDisks(storageDomainId, getStoragePool().getId()); registerAllOvfDisks(ovfStoreDiskImages, storageDomainId); // Update unregistered entities for (OvfEntityData ovf : unregisteredEntitiesFromOvfDisk) { getUnregisteredOVFDataDao().removeEntity(ovf.getEntityId(), storageDomainId); getUnregisteredOVFDataDao().saveOVFData(ovf); log.info("Adding OVF data of entity id '{}' and entity name '{}'", ovf.getEntityId(), ovf.getEntityName()); } return null; } }); } } @Override protected void setActionMessageParameters() { addCanDoActionMessage(EngineMessage.VAR__TYPE__STORAGE__DOMAIN); addCanDoActionMessage(EngineMessage.VAR__ACTION__ATTACH_ACTION_TO); } private boolean checkStorageDomainsInPool() { if (!getParameters().getIsInternal()) { boolean _hasData = false; StorageFormatType storageFormat = null; for (Guid storageDomainId : getParameters().getStorages()) { StorageDomain domain = DbFacade.getInstance().getStorageDomainDao().get(storageDomainId); StorageDomainToPoolRelationValidator storageDomainToPoolRelationValidator = new StorageDomainToPoolRelationValidator(domain.getStorageStaticData(), getStoragePool()); StorageDomainValidator domainValidator = new StorageDomainValidator(domain); if (isStorageDomainNotNull(domain) && validate(domainValidator.checkStorageDomainSharedStatusNotLocked()) && validate(storageDomainToPoolRelationValidator.validateDomainCanBeAttachedToPool())) { if (domain.getStorageDomainType() == StorageDomainType.Data) { _hasData = true; if (storageFormat == null) { storageFormat = domain.getStorageFormat(); } else if (storageFormat != domain.getStorageFormat()) { addCanDoActionMessage(EngineMessage.ERROR_CANNOT_ADD_STORAGE_POOL_WITH_DIFFERENT_STORAGE_FORMAT); return false; } } } else { return false; } } if (!_hasData) { addCanDoActionMessage(EngineMessage.ERROR_CANNOT_ADD_STORAGE_POOL_WITHOUT_DATA_AND_ISO_DOMAINS); return false; } } return true; } @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.USER_ATTACH_STORAGE_DOMAINS_TO_POOL : AuditLogType.USER_ATTACH_STORAGE_DOMAINS_TO_POOL_FAILED; } @Override protected boolean canDoAction() { boolean returnValue = super.canDoAction() && checkStoragePool() && checkStoragePoolStatus(StoragePoolStatus.Uninitialized) && initializeVds() && checkStorageDomainsInPool() && isDomainAttachedToDifferentStoragePool(); return returnValue; } @Override protected Map<String, Pair<String, String>> getExclusiveLocks() { return Collections.singletonMap(getStoragePoolId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.POOL, EngineMessage.ACTION_TYPE_FAILED_OBJECT_LOCKED)); } private boolean isDomainAttachedToDifferentStoragePool() { if (getStoragePool().getStatus() == StoragePoolStatus.Uninitialized) { for (Guid storageDomainId : getParameters().getStorages()) { StorageDomain domain = getStorageDomainDao().get(storageDomainId); if (domain.getStorageDomainType().isDataDomain() && isStorageDomainAttachedToStoragePool(domain)) { return failCanDoAction(EngineMessage.ERROR_CANNOT_ADD_STORAGE_DOMAIN_WITH_ATTACHED_DATA_DOMAIN); } } } return true; } private boolean isStorageDomainAttachedToStoragePool(StorageDomain storageDomain) { List<StorageDomain> storageDomainList = getBackend().runInternalQuery(VdcQueryType.GetStorageDomainsWithAttachedStoragePoolGuid, new StorageDomainsAndStoragePoolIdQueryParameters(storageDomain, getStoragePoolId(), getVds().getId(), false)) .getReturnValue(); return !storageDomainList.isEmpty(); } }
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/storage/pool/AddStoragePoolWithStoragesCommand.java
package org.ovirt.engine.core.bll.storage.pool; import java.util.Collections; import java.util.List; import java.util.Map; import org.ovirt.engine.core.bll.Backend; import org.ovirt.engine.core.bll.LockMessagesMatchUtil; import org.ovirt.engine.core.bll.NonTransactiveCommandAttribute; import org.ovirt.engine.core.bll.context.CommandContext; import org.ovirt.engine.core.bll.storage.connection.StorageHelperDirector; import org.ovirt.engine.core.bll.validator.storage.StorageDomainToPoolRelationValidator; import org.ovirt.engine.core.bll.validator.storage.StorageDomainValidator; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.action.LockProperties; import org.ovirt.engine.core.common.action.LockProperties.Scope; import org.ovirt.engine.core.common.action.StorageDomainPoolParametersBase; import org.ovirt.engine.core.common.action.StoragePoolWithStoragesParameter; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.businessentities.OvfEntityData; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.StorageDomainStatic; import org.ovirt.engine.core.common.businessentities.StorageDomainStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.StorageFormatType; import org.ovirt.engine.core.common.businessentities.StoragePool; import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMap; import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMapId; import org.ovirt.engine.core.common.businessentities.StoragePoolStatus; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.errors.EngineError; import org.ovirt.engine.core.common.errors.EngineException; import org.ovirt.engine.core.common.errors.EngineMessage; import org.ovirt.engine.core.common.locks.LockingGroup; import org.ovirt.engine.core.common.queries.StorageDomainsAndStoragePoolIdQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.utils.VersionStorageFormatUtil; import org.ovirt.engine.core.common.vdscommands.CreateStoragePoolVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.TransactionScopeOption; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; @NonTransactiveCommandAttribute(forceCompensation = true) public class AddStoragePoolWithStoragesCommand<T extends StoragePoolWithStoragesParameter> extends UpdateStoragePoolCommand<T> { public AddStoragePoolWithStoragesCommand(T parameters) { this(parameters, null); } public AddStoragePoolWithStoragesCommand(T parameters, CommandContext commandContext) { super(parameters, commandContext); } /** * Constructor for command creation when compensation is applied on startup * * @param commandId */ protected AddStoragePoolWithStoragesCommand(Guid commandId) { super(commandId); } @Override protected LockProperties applyLockProperties(LockProperties lockProperties) { return lockProperties.withScope(Scope.Execution); } private StorageDomain masterStorageDomain = null; VDSReturnValue retVal; @Override protected void executeCommand() { if (UpdateStorageDomainsInDb()) { // setting storage pool status to maintenance StoragePool storagePool = getStoragePool(); getCompensationContext().snapshotEntity(storagePool); TransactionSupport.executeInNewTransaction(new TransactionMethod<Object>() { @Override public Object runInTransaction() { getStoragePool().setStatus(StoragePoolStatus.Maintenance); getStoragePool().setStoragePoolFormatType(masterStorageDomain.getStorageFormat()); DbFacade.getInstance().getStoragePoolDao().update(getStoragePool()); getCompensationContext().stateChanged(); StoragePoolStatusHandler.poolStatusChanged(getStoragePool().getId(), getStoragePool().getStatus()); return null; } }); // Following code performs only read operations, therefore no need for new transaction boolean result = false; retVal = null; for (VDS vds : getAllRunningVdssInPool()) { setVds(vds); for (Guid storageDomainId : getParameters().getStorages()) { // now the domain should have the mapping // with the pool in db StorageDomain storageDomain = DbFacade.getInstance() .getStorageDomainDao() .getForStoragePool(storageDomainId, getStoragePool().getId()); StorageHelperDirector.getInstance() .getItem(storageDomain.getStorageType()) .connectStorageToDomainByVdsId(storageDomain, getVds().getId()); } retVal = addStoragePoolInIrs(); if (!retVal.getSucceeded() && retVal.getVdsError().getCode() == EngineError.StorageDomainAccessError) { log.warn("Error creating storage pool on vds '{}' - continuing", vds.getName()); continue; } else { // storage pool creation succeeded or failed // but didn't throw exception result = retVal.getSucceeded(); break; } } setSucceeded(result); if (!result) { if (retVal != null && retVal.getVdsError().getCode() != null) { throw new EngineException(retVal.getVdsError().getCode(), retVal.getVdsError().getMessage()); } else { // throw exception to cause rollback and stop the // command throw new EngineException(EngineError.ENGINE_ERROR_CREATING_STORAGE_POOL); } } else { registerOvfStoreDisks(); } } // Create pool phase completed, no rollback is needed here, so compensation information needs to be cleared! TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().resetCompensation(); return null; } }); freeLock(); // if create succeeded activate if (getSucceeded()) { ActivateStorageDomains(); } } private boolean UpdateStorageDomainsInDb() { boolean result = TransactionSupport.executeInNewTransaction(new TransactionMethod<Boolean>() { @Override public Boolean runInTransaction() { for (Guid storageDomainId : getParameters().getStorages()) { StorageDomain storageDomain = DbFacade.getInstance().getStorageDomainDao().get( storageDomainId); if (storageDomain != null) { StoragePoolIsoMap mapFromDB = DbFacade.getInstance() .getStoragePoolIsoMapDao() .get(new StoragePoolIsoMapId(storageDomain.getId(), getStoragePool().getId())); boolean existingInDb = mapFromDB != null; if (existingInDb) { getCompensationContext().snapshotEntity(mapFromDB); } final StorageDomainStatic staticDomain = storageDomain.getStorageStaticData(); boolean staticDomainChanged = false; StorageFormatType requiredFormatType = VersionStorageFormatUtil.getRequiredForVersion (getStoragePool().getCompatibilityVersion(), storageDomain.getStorageType()); if (staticDomain.getStorageFormat().compareTo(requiredFormatType) < 0) { if (!staticDomainChanged) { getCompensationContext().snapshotEntity(staticDomain); } staticDomain.setStorageFormat(requiredFormatType); staticDomainChanged = true; } storageDomain.setStoragePoolId(getStoragePool().getId()); if (masterStorageDomain == null && storageDomain.getStorageDomainType() == StorageDomainType.Data) { if (!staticDomainChanged) { getCompensationContext().snapshotEntity(staticDomain); } storageDomain.setStorageDomainType(StorageDomainType.Master); staticDomainChanged = true; masterStorageDomain = storageDomain; // The update of storage pool should be without compensation, // this is why we run it in a different SUPRESS transaction. updateStoragePoolMasterDomainVersionInDiffTransaction(); } if (staticDomainChanged) { getStorageDomainStaticDao().update(staticDomain); } storageDomain.setStatus(StorageDomainStatus.Locked); if (existingInDb) { DbFacade.getInstance() .getStoragePoolIsoMapDao() .update(storageDomain.getStoragePoolIsoMapData()); } else { DbFacade.getInstance() .getStoragePoolIsoMapDao() .save(storageDomain.getStoragePoolIsoMapData()); getCompensationContext().snapshotNewEntity(storageDomain.getStoragePoolIsoMapData()); } } else { return false; } } getCompensationContext().stateChanged(); return true; } }); return result && masterStorageDomain != null; } /** * Save the master version out of the transaction */ private VDSReturnValue addStoragePoolInIrs() { return runVdsCommand(VDSCommandType.CreateStoragePool, new CreateStoragePoolVDSCommandParameters(getVds().getId(), getStoragePool().getId(), getStoragePool().getName(), masterStorageDomain.getId(), getParameters().getStorages(), getStoragePool() .getMasterDomainVersion())); } private boolean ActivateStorageDomains() { boolean returnValue = true; for (final Guid storageDomainId : getParameters().getStorages()) { StorageDomainPoolParametersBase activateParameters = new StorageDomainPoolParametersBase(storageDomainId, getStoragePool().getId()); activateParameters.setSessionId(getParameters().getSessionId()); activateParameters.setTransactionScopeOption(TransactionScopeOption.RequiresNew); returnValue = Backend.getInstance() .runInternalAction(VdcActionType.ActivateStorageDomain, activateParameters).getSucceeded(); // if activate domain failed then set domain status to inactive if (!returnValue) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { DbFacade.getInstance() .getStoragePoolIsoMapDao() .updateStatus( new StoragePoolIsoMapId(storageDomainId, getStoragePool().getId()), StorageDomainStatus.Inactive); return null; } }); } } return returnValue; } private void registerOvfStoreDisks() { for (final Guid storageDomainId : getParameters().getStorages()) { resetOvfStoreDisks(); final List<OvfEntityData> unregisteredEntitiesFromOvfDisk = getEntitiesFromStorageOvfDisk(storageDomainId, getStoragePool().getId()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { List<DiskImage> ovfStoreDiskImages = getAllOVFDisks(storageDomainId, getStoragePool().getId()); registerAllOvfDisks(ovfStoreDiskImages, storageDomainId); // Update unregistered entities for (OvfEntityData ovf : unregisteredEntitiesFromOvfDisk) { getUnregisteredOVFDataDao().removeEntity(ovf.getEntityId(), storageDomainId); getUnregisteredOVFDataDao().saveOVFData(ovf); log.info("Adding OVF data of entity id '{}' and entity name '{}'", ovf.getEntityId(), ovf.getEntityName()); } return null; } }); } } @Override protected void setActionMessageParameters() { addCanDoActionMessage(EngineMessage.VAR__TYPE__STORAGE__DOMAIN); addCanDoActionMessage(EngineMessage.VAR__ACTION__ATTACH_ACTION_TO); } private boolean checkStorageDomainsInPool() { if (!getParameters().getIsInternal()) { boolean _hasData = false; StorageFormatType storageFormat = null; for (Guid storageDomainId : getParameters().getStorages()) { StorageDomain domain = DbFacade.getInstance().getStorageDomainDao().get(storageDomainId); StorageDomainToPoolRelationValidator storageDomainToPoolRelationValidator = new StorageDomainToPoolRelationValidator(domain.getStorageStaticData(), getStoragePool()); StorageDomainValidator domainValidator = new StorageDomainValidator(domain); if (isStorageDomainNotNull(domain) && validate(domainValidator.checkStorageDomainSharedStatusNotLocked()) && validate(storageDomainToPoolRelationValidator.validateDomainCanBeAttachedToPool())) { if (domain.getStorageDomainType() == StorageDomainType.Data) { _hasData = true; if (storageFormat == null) { storageFormat = domain.getStorageFormat(); } else if (storageFormat != domain.getStorageFormat()) { addCanDoActionMessage(EngineMessage.ERROR_CANNOT_ADD_STORAGE_POOL_WITH_DIFFERENT_STORAGE_FORMAT); return false; } } } else { return false; } } if (!_hasData) { addCanDoActionMessage(EngineMessage.ERROR_CANNOT_ADD_STORAGE_POOL_WITHOUT_DATA_AND_ISO_DOMAINS); return false; } } return true; } @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.USER_ATTACH_STORAGE_DOMAINS_TO_POOL : AuditLogType.USER_ATTACH_STORAGE_DOMAINS_TO_POOL_FAILED; } @Override protected boolean canDoAction() { boolean returnValue = super.canDoAction() && checkStoragePool() && checkStoragePoolStatus(StoragePoolStatus.Uninitialized) && initializeVds() && checkStorageDomainsInPool() && isDomainAttachedToDifferentStoragePool(); return returnValue; } @Override protected Map<String, Pair<String, String>> getExclusiveLocks() { return Collections.singletonMap(getStoragePoolId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.POOL, EngineMessage.ACTION_TYPE_FAILED_OBJECT_LOCKED)); } private boolean isDomainAttachedToDifferentStoragePool() { if (getStoragePool().getStatus() == StoragePoolStatus.Uninitialized) { for (Guid storageDomainId : getParameters().getStorages()) { StorageDomain domain = getStorageDomainDao().get(storageDomainId); if (domain.getStorageDomainType().isDataDomain() && isStorageDomainAttachedToStoragePool(domain)) { return failCanDoAction(EngineMessage.ERROR_CANNOT_ADD_STORAGE_DOMAIN_WITH_ATTACHED_DATA_DOMAIN); } } } return true; } private boolean isStorageDomainAttachedToStoragePool(StorageDomain storageDomain) { List<StorageDomain> storageDomainList = getBackend().runInternalQuery(VdcQueryType.GetStorageDomainsWithAttachedStoragePoolGuid, new StorageDomainsAndStoragePoolIdQueryParameters(storageDomain, getStoragePoolId(), getVds().getId(), false)) .getReturnValue(); return !storageDomainList.isEmpty(); } }
core: AddStoragePoolWithStoragesCommand methods naming conventions Fixed naming conventions of the AddStoragePoolWithStoragesCommand class' methods as per the recommended Java naming conventions. Change-Id: I76dfd863ca911ecd220f2594d4a54861ab931d54 Signed-off-by: Allon Mureinik <[email protected]>
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/storage/pool/AddStoragePoolWithStoragesCommand.java
core: AddStoragePoolWithStoragesCommand methods naming conventions
<ide><path>ackend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/storage/pool/AddStoragePoolWithStoragesCommand.java <ide> <ide> @Override <ide> protected void executeCommand() { <del> if (UpdateStorageDomainsInDb()) { <add> if (updateStorageDomainsInDb()) { <ide> // setting storage pool status to maintenance <ide> StoragePool storagePool = getStoragePool(); <ide> getCompensationContext().snapshotEntity(storagePool); <ide> freeLock(); <ide> // if create succeeded activate <ide> if (getSucceeded()) { <del> ActivateStorageDomains(); <del> } <del> } <del> <del> private boolean UpdateStorageDomainsInDb() { <add> activateStorageDomains(); <add> } <add> } <add> <add> private boolean updateStorageDomainsInDb() { <ide> boolean result = TransactionSupport.executeInNewTransaction(new TransactionMethod<Boolean>() { <ide> <ide> @Override <ide> .getMasterDomainVersion())); <ide> } <ide> <del> private boolean ActivateStorageDomains() { <add> private boolean activateStorageDomains() { <ide> boolean returnValue = true; <ide> for (final Guid storageDomainId : getParameters().getStorages()) { <ide> StorageDomainPoolParametersBase activateParameters = new StorageDomainPoolParametersBase(storageDomainId,
Java
apache-2.0
4e7d85e953e11447ca7624700845c4a9b31da4e7
0
cibuddy/cibuddy,cibuddy/cibuddy
package com.cibuddy.project.configuration.impl; import com.cibuddy.core.build.configuration.BuildTestConfiguration; import com.cibuddy.project.configuration.schema.BuildTestConfigurationType; import com.cibuddy.project.configuration.schema.Setup; import java.io.File; import java.util.*; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import org.apache.felix.fileinstall.ArtifactInstaller; import org.osgi.framework.ServiceRegistration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author mirkojahn */ public class ProjectConfigurationListener implements ArtifactInstaller { private static final Logger LOG = LoggerFactory.getLogger(ProjectConfigurationListener.class); private static final String packageName = "com.cibuddy.project.configuration.schema"; Map<File,List<ServiceRegistration>> configuredFiles = new HashMap<File,List<ServiceRegistration>>(); @Override public boolean canHandle(File file) { LOG.info("Handle: " + file.getAbsolutePath()); if (file == null) { return false; } else if (file.getName().endsWith(".xml")) { try { BuildTestConfigurationType btct = new BuildTestConfigurationType(); ClassLoader cl = btct.getClass().getClassLoader(); if(cl == null){ // pretty bad. We have a bootstrap classloader. Not much we can do. LOG.warn("Found BootClassLoader, trying the bundle class loader instead. This might not work! " + "Better upgrade your JVM!"); cl = this.getClass().getClassLoader(); } JAXBContext jc = JAXBContext.newInstance(packageName,cl); Unmarshaller unmarshaller = jc.createUnmarshaller(); // make sure the schema matches. Otherwise an exception will be raised. Setup config = (Setup) unmarshaller.unmarshal(file); return true; } catch (Exception ex) { // couldn't parse xml with expected schema... do nothing. // FIXME: this is nasty! in case this is not an xml according to the schema this is wrong! LOG.debug("Problems setting up configuration file.",ex); } return false; } else { return false; } } @Override public void install(File file) throws Exception { LOG.info("Handle Install: " + file.getAbsolutePath()); try { JAXBContext jc = JAXBContext.newInstance(packageName,this.getClass().getClassLoader()); Unmarshaller unmarshaller = jc.createUnmarshaller(); Setup config = (Setup) unmarshaller.unmarshal(file); List<BuildTestConfigurationType> configurations = config.getConfiguration(); Iterator<BuildTestConfigurationType> iter = configurations.iterator(); List<ServiceRegistration> configServices = new ArrayList<ServiceRegistration>(); while(iter.hasNext()) { BuildTestConfigurationType bct = iter.next(); BuildTestConfiguration dbtcConfig = new DefaultBuildTestConfiguration(bct); ServiceRegistration sr = registerServer(dbtcConfig, file); configServices.add(sr); } configuredFiles.put(file, configServices); } catch (Exception e) { LOG.warn("Problems setting up configuration file.",e); } } @Override public void update(File file) throws Exception { // This could be more granular, but for now this is ok. LOG.info("Handle Update: " + file.getAbsolutePath()); uninstall(file); install(file); } @Override public void uninstall(File file) throws Exception { LOG.info("Handle Uninstall: " + file.getAbsolutePath()); List<ServiceRegistration> srs = configuredFiles.get(file); if(srs != null && srs.size() > 0) { Iterator<ServiceRegistration> srsIterator = srs.iterator(); while(srsIterator.hasNext()) { ServiceRegistration sr = srsIterator.next(); try { sr.unregister(); } catch (Exception e) { // do nothing } } configuredFiles.remove(file); } } private ServiceRegistration registerServer(BuildTestConfiguration dbtc, File f) { Dictionary dict = new Hashtable(); safePut(dict,BuildTestConfiguration.BUILD_TEST_ALIAS, dbtc.getAlias()); safePut(dict,BuildTestConfiguration.BUILD_TEST_SOURCE, f.getPath()); return Activator.getBundleContext().registerService(BuildTestConfiguration.class.getName(), (BuildTestConfiguration)dbtc, dict); } private void safePut(Dictionary dict, String key, Object value) { if(key != null && value != null){ dict.put(key, value); } } }
main/project.configuration/src/main/java/com/cibuddy/project/configuration/impl/ProjectConfigurationListener.java
package com.cibuddy.project.configuration.impl; import com.cibuddy.core.build.configuration.BuildTestConfiguration; import com.cibuddy.project.configuration.schema.BuildTestConfigurationType; import com.cibuddy.project.configuration.schema.Setup; import java.io.File; import java.util.*; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import org.apache.felix.fileinstall.ArtifactInstaller; import org.osgi.framework.ServiceRegistration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author mirkojahn */ public class ProjectConfigurationListener implements ArtifactInstaller { private static final Logger LOG = LoggerFactory.getLogger(ProjectConfigurationListener.class); private static final String packageName = "com.cibuddy.project.configuration.schema"; Map<File,List<ServiceRegistration>> configuredFiles = new HashMap<File,List<ServiceRegistration>>(); @Override public boolean canHandle(File file) { LOG.info("Handle: " + file.getAbsolutePath()); if (file == null) { return false; } else if (file.getName().endsWith(".xml")) { try { JAXBContext jc = JAXBContext.newInstance(packageName, BuildTestConfigurationType.class.getClass().getClassLoader()); Unmarshaller unmarshaller = jc.createUnmarshaller(); Setup config = (Setup) unmarshaller.unmarshal(file); return true; } catch (Exception ex) { // couldn't parse xml with expected schema... do nothing. // FIXME: this is nasty! in case this is not an xml according to the schema this is wrong! LOG.debug("Problems setting up configuration file.",ex); } return false; } else { return false; } } @Override public void install(File file) throws Exception { LOG.info("Handle Install: " + file.getAbsolutePath()); try { JAXBContext jc = JAXBContext.newInstance(packageName,this.getClass().getClassLoader()); Unmarshaller unmarshaller = jc.createUnmarshaller(); Setup config = (Setup) unmarshaller.unmarshal(file); List<BuildTestConfigurationType> configurations = config.getConfiguration(); Iterator<BuildTestConfigurationType> iter = configurations.iterator(); List<ServiceRegistration> configServices = new ArrayList<ServiceRegistration>(); while(iter.hasNext()) { BuildTestConfigurationType bct = iter.next(); BuildTestConfiguration dbtcConfig = new DefaultBuildTestConfiguration(bct); ServiceRegistration sr = registerServer(dbtcConfig, file); configServices.add(sr); } configuredFiles.put(file, configServices); } catch (Exception e) { LOG.warn("Problems setting up configuration file.",e); } } @Override public void update(File file) throws Exception { // This could be more granular, but for now this is ok. LOG.info("Handle Update: " + file.getAbsolutePath()); uninstall(file); install(file); } @Override public void uninstall(File file) throws Exception { LOG.info("Handle Uninstall: " + file.getAbsolutePath()); List<ServiceRegistration> srs = configuredFiles.get(file); if(srs != null && srs.size() > 0) { Iterator<ServiceRegistration> srsIterator = srs.iterator(); while(srsIterator.hasNext()) { ServiceRegistration sr = srsIterator.next(); try { sr.unregister(); } catch (Exception e) { // do nothing } } configuredFiles.remove(file); } } private ServiceRegistration registerServer(BuildTestConfiguration dbtc, File f) { Dictionary dict = new Hashtable(); safePut(dict,BuildTestConfiguration.BUILD_TEST_ALIAS, dbtc.getAlias()); safePut(dict,BuildTestConfiguration.BUILD_TEST_SOURCE, f.getPath()); return Activator.getBundleContext().registerService(BuildTestConfiguration.class.getName(), (BuildTestConfiguration)dbtc, dict); } private void safePut(Dictionary dict, String key, Object value) { if(key != null && value != null){ dict.put(key, value); } } }
Sort of fixed a class loader problem with old JAXB implementations provided by the JVM.
main/project.configuration/src/main/java/com/cibuddy/project/configuration/impl/ProjectConfigurationListener.java
Sort of fixed a class loader problem with old JAXB implementations provided by the JVM.
<ide><path>ain/project.configuration/src/main/java/com/cibuddy/project/configuration/impl/ProjectConfigurationListener.java <ide> return false; <ide> } else if (file.getName().endsWith(".xml")) { <ide> try { <del> JAXBContext jc = JAXBContext.newInstance(packageName, BuildTestConfigurationType.class.getClass().getClassLoader()); <add> BuildTestConfigurationType btct = new BuildTestConfigurationType(); <add> ClassLoader cl = btct.getClass().getClassLoader(); <add> if(cl == null){ <add> // pretty bad. We have a bootstrap classloader. Not much we can do. <add> LOG.warn("Found BootClassLoader, trying the bundle class loader instead. This might not work! " <add> + "Better upgrade your JVM!"); <add> cl = this.getClass().getClassLoader(); <add> } <add> JAXBContext jc = JAXBContext.newInstance(packageName,cl); <ide> Unmarshaller unmarshaller = jc.createUnmarshaller(); <add> // make sure the schema matches. Otherwise an exception will be raised. <ide> Setup config = (Setup) unmarshaller.unmarshal(file); <ide> return true; <ide> } catch (Exception ex) {
JavaScript
mit
4903c33585c8e0679a93af882da6b9e1387f2fde
0
dbiscalchin/urlinput,dbiscalchin/urlinput
/** * URL Input plugin for jQuery * @author Daniel Catarino Biscalchin * * Provides a widget for text inputs holding URL values. * It enforces the protocol and adds a link to test the URL. * * Basic usage: $('#my-text-input').urlinput() */ (function ($) { $.fn.urlinput = function (options) { // Set options based on theme or use default var theme = 'default'; if (options && options.theme) { theme = options.theme; } var settings = $.extend({}, $.fn.urlinput.themes['default'], $.fn.urlinput.themes[theme], options); // Add wrapper to input element var $widgetWrapper = $(settings.widgetWrapper); $widgetWrapper.addClass('urlinput-widget-wrapper'); this.wrap($widgetWrapper); // Add extra classes to input element this.addClass('urlinput-field ' + settings.fieldClass); // Add icon before input if (settings.showFavicon) { var $iconWrapper = $(settings.faviconWrapper); $iconWrapper.addClass('urlinput-icon-wrapper'); $iconWrapper.html('<img src="//www.google.com/s2/favicons" />'); this.before($iconWrapper); } // Add link after input var $linkWrapper = $(settings.linkWrapper); $linkWrapper.addClass('urlinput-link-wrapper'); $linkWrapper.html('<a href="' + this.val() +'" target="_blank" class="' + settings.linkClass + '">' + settings.linkText + '</a>'); this.after($linkWrapper); // Iterate over each element to add a different value and handler this.each(function (i, elem) { var $this = $(this); // current element // Set default value var val = $this.val(); var protocol = val.slice(0, 4); if (!(protocol == 'http')) { // Set val with http protocol val = 'http://' + val; $this.val(val); } // Add handler $this.change(function (ev) { var $this = $(this); // changed element var val = $this.val(); // Add http protocol if not informed var protocol = val.slice(0, 4); if (!(protocol == 'http')) { // Set val with http protocol val = 'http://' + val; $this.val(val); } // Set link URL var $link = $this.next('.urlinput-link-wrapper').find('a').attr('href', $this.val()); // Update favicon if (settings.showFavicon) { var faviconSrc = '//www.google.com/s2/favicons?domain=' + $link.prop('hostname'); $this.prev('.urlinput-icon-wrapper').find('img').attr('src', faviconSrc); } }); // Erase value when submitting if it has only the protocol $this.closest('form').submit(function (ev) { if ($this.val() == 'http://') { $this.val(''); } }); }); return this; } $.fn.urlinput.themes = { default: { fieldClass: '', linkText: 'Try it!', linkClass: '', linkWrapper: $('<span></span>'), showFavicon: true, faviconWrapper: $('<span></span>'), widgetWrapper: $('<div></div>'), }, bootstrap: { fieldClass: 'form-control', linkText: '<span class="glyphicon glyphicon-new-window"></span>', linkClass: 'btn btn-default', linkWrapper: $('<span class="input-group-btn"></span>'), faviconWrapper: $('<span class="input-group-addon"></span>'), widgetWrapper: $('<div class="input-group"></div>'), }, }; }(jQuery));
src/jquery.urlinput.js
/** * URL Input plugin for jQuery * @author Daniel Catarino Biscalchin * * Provides a widget for text inputs holding URL values. * It enforces the protocol and adds a link to test the URL. * * Basic usage: $('#my-text-input').urlinput() */ (function ($) { $.fn.urlinput = function (options) { // Set options based on theme or use default var theme = 'default'; if (options && options.theme) { theme = options.theme; } var settings = $.extend({}, $.fn.urlinput.themes[theme], options); // Add icon before input if (settings.showFavicon) { var $wrapper = $(settings.faviconWrapper); $wrapper.addClass('urlinput-icon-wrapper'); $wrapper.html('<img src="//www.google.com/s2/favicons" />'); this.before($wrapper); } // Add link after input var $wrapper = $(settings.linkWrapper); $wrapper.addClass('urlinput-link-wrapper'); $wrapper.html('<a href="' + this.val() +'" target="_blank" class="' + settings.linkClass + '">' + settings.linkText + '</a>'); this.after($wrapper); // Iterate over each element to add a different value and handler this.each(function (i, elem) { var $this = $(this); // current element // Set default value var val = $this.val(); var protocol = val.slice(0, 4); if (!(protocol == 'http')) { // Set val with http protocol val = 'http://' + val; $this.val(val); } // Add handler $this.change(function (ev) { var $this = $(this); // changed element var val = $this.val(); // Add http protocol if not informed var protocol = val.slice(0, 4); if (!(protocol == 'http')) { // Set val with http protocol val = 'http://' + val; $this.val(val); } // Set link URL var $link = $this.next('.urlinput-link-wrapper').find('a').attr('href', $this.val()); // Update favicon if (settings.showFavicon) { var faviconSrc = '//www.google.com/s2/favicons?domain=' + $link.prop('hostname'); $this.prev('.urlinput-icon-wrapper').find('img').attr('src', faviconSrc); } }); // Erase value when submitting if it has only the protocol $this.closest('form').submit(function (ev) { if ($this.val() == 'http://') { $this.val(''); } }); }); return this; } $.fn.urlinput.themes = { default: { linkText: 'Try it!', linkClass: '', linkWrapper: $('<span></span>'), showFavicon: true, faviconWrapper: $('<span></span>'), }, bootstrap: { linkText: '<span class="glyphicon glyphicon-new-window"></span>', linkClass: 'btn btn-default', linkWrapper: $('<span class="input-group-btn"></span>'), showFavicon: true, faviconWrapper: $('<span class="input-group-addon"></span>'), }, }; }(jQuery));
new settings fieldClass and widgetWrapper
src/jquery.urlinput.js
new settings
<ide><path>rc/jquery.urlinput.js <ide> if (options && options.theme) { <ide> theme = options.theme; <ide> } <del> var settings = $.extend({}, $.fn.urlinput.themes[theme], options); <add> var settings = $.extend({}, $.fn.urlinput.themes['default'], <add> $.fn.urlinput.themes[theme], options); <add> <add> // Add wrapper to input element <add> var $widgetWrapper = $(settings.widgetWrapper); <add> $widgetWrapper.addClass('urlinput-widget-wrapper'); <add> this.wrap($widgetWrapper); <add> <add> // Add extra classes to input element <add> this.addClass('urlinput-field ' + settings.fieldClass); <ide> <ide> // Add icon before input <ide> if (settings.showFavicon) { <del> var $wrapper = $(settings.faviconWrapper); <del> $wrapper.addClass('urlinput-icon-wrapper'); <del> $wrapper.html('<img src="//www.google.com/s2/favicons" />'); <del> this.before($wrapper); <add> var $iconWrapper = $(settings.faviconWrapper); <add> $iconWrapper.addClass('urlinput-icon-wrapper'); <add> $iconWrapper.html('<img src="//www.google.com/s2/favicons" />'); <add> this.before($iconWrapper); <ide> } <ide> <ide> // Add link after input <del> var $wrapper = $(settings.linkWrapper); <del> $wrapper.addClass('urlinput-link-wrapper'); <del> $wrapper.html('<a href="' + this.val() +'" target="_blank" class="' + settings.linkClass + '">' + settings.linkText + '</a>'); <del> this.after($wrapper); <add> var $linkWrapper = $(settings.linkWrapper); <add> $linkWrapper.addClass('urlinput-link-wrapper'); <add> $linkWrapper.html('<a href="' + this.val() +'" target="_blank" class="' + settings.linkClass + '">' + settings.linkText + '</a>'); <add> this.after($linkWrapper); <ide> <ide> // Iterate over each element to add a different value and handler <ide> this.each(function (i, elem) { <ide> <ide> $.fn.urlinput.themes = { <ide> default: { <add> fieldClass: '', <ide> linkText: 'Try it!', <ide> linkClass: '', <ide> linkWrapper: $('<span></span>'), <ide> showFavicon: true, <ide> faviconWrapper: $('<span></span>'), <add> widgetWrapper: $('<div></div>'), <ide> }, <ide> bootstrap: { <add> fieldClass: 'form-control', <ide> linkText: '<span class="glyphicon glyphicon-new-window"></span>', <ide> linkClass: 'btn btn-default', <ide> linkWrapper: $('<span class="input-group-btn"></span>'), <del> showFavicon: true, <ide> faviconWrapper: $('<span class="input-group-addon"></span>'), <add> widgetWrapper: $('<div class="input-group"></div>'), <ide> }, <ide> }; <ide> }(jQuery));
Java
apache-2.0
9aedb106ec2167b4c26151be019b91fa85a582ab
0
mojohaus/servicedocgen-maven-plugin,mojohaus/servicedocgen-maven-plugin
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.codehaus.mojo.servicedocgen.introspection; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.mmm.util.reflect.api.GenericType; import net.sf.mmm.util.reflect.api.ReflectionUtil; import org.codehaus.mojo.servicedocgen.Util; import com.thoughtworks.qdox.model.DocletTag; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaMethod; import com.thoughtworks.qdox.model.JavaParameter; /** * Rich representation of a {@link Method} with both byte-code and source-code analysis information. * * @author hohwille */ public class JMethod { private final JType type; private final JavaMethod sourceMethod; private final Method byteMethod; private final List<JParameter> parameters; private final List<JException> exceptions; private final JReturn returns; private final String comment; /** * The constructor. * * @param byteMethod - see {@link #getByteMethod()}. * @param type - see {@link #getType()}. */ public JMethod( Method byteMethod, JType type ) { this( byteMethod, type, byteMethod ); } /** * The constructor. * * @param byteMethod - see {@link #getByteMethod()}. * @param type - see {@link #getType()}. * @param annotatedParentMethod the {@link Method} containing the JAX-RS annotation that may be a parent * {@link Method} of <code>byteMethod</code>. */ public JMethod( Method byteMethod, JType type, Method annotatedParentMethod ) { super(); this.type = type; this.byteMethod = byteMethod; JavaClass sourceType = type.getSourceType(); GenericType<?> byteType = type.getByteType(); ReflectionUtil reflectionUtil = type.getReflectionUtil(); JavaDocHelper javaDocHelper = type.getJavaDocHelper(); this.sourceMethod = findSourceMethod( sourceType, byteMethod ); // get source information List<JavaParameter> parameterSourceInfos = null; Map<String, String> parameterMap = null; List<JavaClass> exceptionSourceTypes = null; Map<String, String> exceptionMap = null; JavaClass returnSourceType = null; String returnComment = ""; if ( this.sourceMethod != null ) { this.comment = javaDocHelper.parseJavaDoc( sourceType, byteType, this.sourceMethod.getComment() ); parameterSourceInfos = this.sourceMethod.getParameters(); parameterMap = getTagListAsMap( this.sourceMethod.getTagsByName( "param" ), false ); exceptionSourceTypes = this.sourceMethod.getExceptions(); exceptionMap = getTagListAsMap( this.sourceMethod.getTagsByName( "throws" ), true ); DocletTag returnTag = this.sourceMethod.getTagByName( "return" ); if ( returnTag != null ) { returnComment = javaDocHelper.parseJavaDoc( sourceType, byteType, returnTag.getValue() ); } returnSourceType = this.sourceMethod.getReturns(); } else { this.comment = ""; } // create parameters Type[] parameterByteTypes = byteMethod.getGenericParameterTypes(); Annotation[][] parameterAnnotations = annotatedParentMethod.getParameterAnnotations(); this.parameters = new ArrayList<JParameter>( parameterByteTypes.length ); this.sourceMethod.getParameters(); for ( int i = 0; i < parameterByteTypes.length; i++ ) { GenericType<?> parameterByteType = reflectionUtil.createGenericType( parameterByteTypes[i], byteType ); JavaParameter parameterSourceType = get( parameterSourceInfos, i ); String parameterComment = ""; if ( ( parameterSourceType != null ) && ( parameterMap != null ) ) { // QDox bug - not working... // comment = sourceParameter.getComment(); parameterComment = javaDocHelper.parseJavaDoc( sourceType, byteType, parameterMap.get( parameterSourceType.getName() ) ); } this.parameters.add( new JParameter( parameterByteType, parameterAnnotations[i], parameterSourceType, parameterComment, i ) ); } // create exceptions Type[] exceptionByteTypes = byteMethod.getGenericExceptionTypes(); this.exceptions = new ArrayList<JException>( exceptionByteTypes.length ); for ( int i = 0; i < exceptionByteTypes.length; i++ ) { JavaClass exceptionSourceType = get( exceptionSourceTypes, i ); GenericType<?> exceptionByteType = reflectionUtil.createGenericType( exceptionByteTypes[i], byteType ); String exceptionComment = ""; if ( exceptionMap != null ) { exceptionComment = javaDocHelper.parseJavaDoc( sourceType, byteType, exceptionMap.get( exceptionByteType.getAssignmentClass().getSimpleName() ) ); } this.exceptions.add( new JException( exceptionByteType, exceptionSourceType, exceptionComment ) ); } // create return GenericType<?> returnByteType = reflectionUtil.createGenericType( byteMethod.getGenericReturnType(), byteType ); this.returns = new JReturn( returnByteType, returnSourceType, returnComment ); } private static <T> T get( List<T> list, int index ) { if ( list == null ) { return null; } if ( index >= list.size() ) { return null; } return list.get( index ); } private static JavaMethod findSourceMethod( JavaClass sourceClass, Method byteMethod ) { for ( JavaMethod sourceMethod : sourceClass.getMethods() ) { if ( sourceMethod.getName().equals( byteMethod.getName() ) ) { List<JavaParameter> sourceParameters = sourceMethod.getParameters(); Class<?>[] byteParameters = byteMethod.getParameterTypes(); if ( sourceParameters.size() == byteParameters.length ) { for ( int i = 0; i < byteParameters.length; i++ ) { String byteTypeName = byteParameters[i].getName(); String sourceTypeName = sourceParameters.get( i ).getType().getFullyQualifiedName(); if ( !byteTypeName.equals( sourceTypeName ) ) { return null; } } return sourceMethod; } } } return null; } private static Map<String, String> getTagListAsMap( List<DocletTag> tagList, boolean simpleName ) { Map<String, String> map = new HashMap<String, String>(); for ( DocletTag tag : tagList ) { String value = tag.getValue(); int firstSpace = value.indexOf( ' ' ); if ( firstSpace > 0 ) { String subTag = value.substring( 0, firstSpace ); if ( simpleName ) { subTag = Util.getSimpleName( subTag ); } String comment = value.substring( firstSpace + 1 ); map.put( subTag, comment ); } } return map; } /** * @return the type */ public JType getType() { return this.type; } /** * @return the sourceMethod */ public JavaMethod getSourceMethod() { return this.sourceMethod; } /** * @return the byteMethod */ public Method getByteMethod() { return this.byteMethod; } /** * @return the parameters */ public List<JParameter> getParameters() { return this.parameters; } /** * @return the exceptions */ public List<JException> getExceptions() { return this.exceptions; } /** * @return the returns */ public JReturn getReturns() { return this.returns; } /** * @return the comment */ public String getComment() { return this.comment; } /** * @return the {@link Method#getName() name} of the {@link Method}. */ public String getName() { return this.byteMethod.getName(); } /** * {@inheritDoc} */ @Override public String toString() { return this.byteMethod.toString(); } }
src/main/java/org/codehaus/mojo/servicedocgen/introspection/JMethod.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.codehaus.mojo.servicedocgen.introspection; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.mmm.util.reflect.api.GenericType; import net.sf.mmm.util.reflect.api.ReflectionUtil; import org.codehaus.mojo.servicedocgen.Util; import com.thoughtworks.qdox.model.DocletTag; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaMethod; import com.thoughtworks.qdox.model.JavaParameter; /** * Rich representation of a {@link Method} with both byte-code and source-code analysis information. * * @author hohwille */ public class JMethod { private final JType type; private final JavaMethod sourceMethod; private final Method byteMethod; private final List<JParameter> parameters; private final List<JException> exceptions; private final JReturn returns; private final String comment; /** * The constructor. * * @param byteMethod - see {@link #getByteMethod()}. * @param type - see {@link #getType()}. */ public JMethod( Method byteMethod, JType type ) { this( byteMethod, type, byteMethod ); } /** * The constructor. * * @param byteMethod - see {@link #getByteMethod()}. * @param type - see {@link #getType()}. * @param annotatedParentMethod the {@link Method} containing the JAX-RS annotation that may be a parent * {@link Method} of <code>byteMethod</code>. */ public JMethod( Method byteMethod, JType type, Method annotatedParentMethod ) { super(); this.type = type; this.byteMethod = byteMethod; JavaClass sourceType = type.getSourceType(); GenericType<?> byteType = type.getByteType(); ReflectionUtil reflectionUtil = type.getReflectionUtil(); JavaDocHelper javaDocHelper = type.getJavaDocHelper(); this.sourceMethod = findSourceMethod( sourceType, byteMethod ); // get source information List<JavaParameter> parameterSourceInfos = null; Map<String, String> parameterMap = null; List<JavaClass> exceptionSourceTypes = null; Map<String, String> exceptionMap = null; JavaClass returnSourceType = null; String returnComment = ""; if ( this.sourceMethod != null ) { this.comment = javaDocHelper.parseJavaDoc( sourceType, byteType, this.sourceMethod.getComment() ); parameterSourceInfos = this.sourceMethod.getParameters(); parameterMap = getTagListAsMap( this.sourceMethod.getTagsByName( "param" ), false ); exceptionSourceTypes = this.sourceMethod.getExceptions(); exceptionMap = getTagListAsMap( this.sourceMethod.getTagsByName( "throws" ), true ); DocletTag returnTag = this.sourceMethod.getTagByName( "return" ); if ( returnTag != null ) { returnComment = javaDocHelper.parseJavaDoc( sourceType, byteType, returnTag.getValue() ); } returnSourceType = this.sourceMethod.getReturns(); } else { this.comment = ""; } // create parameters Type[] parameterByteTypes = byteMethod.getGenericParameterTypes(); Annotation[][] parameterAnnotations = annotatedParentMethod.getParameterAnnotations(); this.parameters = new ArrayList<JParameter>( parameterByteTypes.length ); this.sourceMethod.getParameters(); for ( int i = 0; i < parameterByteTypes.length; i++ ) { GenericType<?> parameterByteType = reflectionUtil.createGenericType( parameterByteTypes[i], byteType ); JavaParameter parameterSourceType = get( parameterSourceInfos, i ); String parameterComment = ""; if ( ( parameterSourceType != null ) && ( parameterMap != null ) ) { // QDox bug - not working... // comment = sourceParameter.getComment(); parameterComment = javaDocHelper.parseJavaDoc( sourceType, byteType, parameterMap.get( parameterSourceType.getName() ) ); } this.parameters.add( new JParameter( parameterByteType, parameterAnnotations[i], parameterSourceType, parameterComment, i ) ); } // create exceptions Type[] exceptionByteTypes = byteMethod.getGenericExceptionTypes(); this.exceptions = new ArrayList<JException>( exceptionByteTypes.length ); for ( int i = 0; i < exceptionByteTypes.length; i++ ) { JavaClass exceptionSourceType = get( exceptionSourceTypes, i ); GenericType<?> exceptionByteType = reflectionUtil.createGenericType( exceptionByteTypes[i], byteType ); String exceptionComment = ""; if ( exceptionMap != null ) { exceptionComment = javaDocHelper.parseJavaDoc( sourceType, byteType, exceptionMap.get( byteType.getAssignmentClass().getSimpleName() ) ); } this.exceptions.add( new JException( exceptionByteType, exceptionSourceType, exceptionComment ) ); } // create return GenericType<?> returnByteType = reflectionUtil.createGenericType( byteMethod.getGenericReturnType(), byteType ); this.returns = new JReturn( returnByteType, returnSourceType, returnComment ); } private static <T> T get( List<T> list, int index ) { if ( list == null ) { return null; } if ( index >= list.size() ) { return null; } return list.get( index ); } private static JavaMethod findSourceMethod( JavaClass sourceClass, Method byteMethod ) { for ( JavaMethod sourceMethod : sourceClass.getMethods() ) { if ( sourceMethod.getName().equals( byteMethod.getName() ) ) { List<JavaParameter> sourceParameters = sourceMethod.getParameters(); Class<?>[] byteParameters = byteMethod.getParameterTypes(); if ( sourceParameters.size() == byteParameters.length ) { for ( int i = 0; i < byteParameters.length; i++ ) { String byteTypeName = byteParameters[i].getName(); String sourceTypeName = sourceParameters.get( i ).getType().getFullyQualifiedName(); if ( !byteTypeName.equals( sourceTypeName ) ) { return null; } } return sourceMethod; } } } return null; } private static Map<String, String> getTagListAsMap( List<DocletTag> tagList, boolean simpleName ) { Map<String, String> map = new HashMap<String, String>(); for ( DocletTag tag : tagList ) { String value = tag.getValue(); int firstSpace = value.indexOf( ' ' ); if ( firstSpace > 0 ) { String subTag = value.substring( 0, firstSpace ); if ( simpleName ) { subTag = Util.getSimpleName( subTag ); } String comment = value.substring( firstSpace + 1 ); map.put( subTag, comment ); } } return map; } /** * @return the type */ public JType getType() { return this.type; } /** * @return the sourceMethod */ public JavaMethod getSourceMethod() { return this.sourceMethod; } /** * @return the byteMethod */ public Method getByteMethod() { return this.byteMethod; } /** * @return the parameters */ public List<JParameter> getParameters() { return this.parameters; } /** * @return the exceptions */ public List<JException> getExceptions() { return this.exceptions; } /** * @return the returns */ public JReturn getReturns() { return this.returns; } /** * @return the comment */ public String getComment() { return this.comment; } /** * @return the {@link Method#getName() name} of the {@link Method}. */ public String getName() { return this.byteMethod.getName(); } /** * {@inheritDoc} */ @Override public String toString() { return this.byteMethod.toString(); } }
#16: fixed javadoc for JException
src/main/java/org/codehaus/mojo/servicedocgen/introspection/JMethod.java
#16: fixed javadoc for JException
<ide><path>rc/main/java/org/codehaus/mojo/servicedocgen/introspection/JMethod.java <ide> if ( exceptionMap != null ) <ide> { <ide> exceptionComment = <del> javaDocHelper.parseJavaDoc( sourceType, byteType, <del> exceptionMap.get( byteType.getAssignmentClass().getSimpleName() ) ); <add> javaDocHelper.parseJavaDoc( sourceType, <add> byteType, <add> exceptionMap.get( exceptionByteType.getAssignmentClass().getSimpleName() ) ); <ide> } <ide> this.exceptions.add( new JException( exceptionByteType, exceptionSourceType, exceptionComment ) ); <ide> }
JavaScript
mit
6b1e318022d253ae757ca015f464ab6a10160b8a
0
aarongoa/psl-lending,aarongoa/psl-lending,aarongoa/psl-lending
'use strict'; const _ = require('lodash'); const fs = require('fs'); const Web3 = require('web3'); const config = require('../config'); const notifier = require('../notifications'); const userHelpers = require('../users/helpers'); const ABI = fs.readFileSync(__dirname + "/ABI.txt", "utf8").trim(); const address = fs.readFileSync(__dirname + "/contractAddress.txt", "utf8").trim(); const web3 = new Web3(); web3.setProvider(new web3.providers.HttpProvider(config.getGethUrl())); const contractInstance = web3.eth.contract(JSON.parse(ABI)).at(address); const allEvents = contractInstance.allEvents(); allEvents.watch((err, result) => { if (err) { return logError("createContractEvent", err); } console.log("Result: ", JSON.stringify(result) + "\n"); console.log("Result Args: ", JSON.stringify(result.args) + "\n"); const { eventName, message, userEthAccount } = eventResultToData(result); console.log(`Notification: ${JSON.stringify(message)} \n`); notifyUser(eventName, message, userEthAccount); }); // helper functions const eventResultToData = (eventResult) => { const eventName = eventResult.event; const argData = JSON.parse(eventResult.args.data); argData.dealId = eventResult.args.deal_id.toString(); const userEthAccount = argData.to; // eth account of person to notify const data = { body: JSON.stringify(_.omit(argData, ['to'])) }; const message = { data }; return { eventName, message, userEthAccount }; }; const notifyUser = (eventName, message, userEthAccount) => { return userHelpers.findUser({ ethAccount: userEthAccount }) .then(user => { if (!user) { return logError(eventName, Error("Cannot send notification to unknown Ethereum user account: " + userEthAccount)); } notifier.notify(user.firebaseToken, message) .then(response => console.log("Then Block: ", JSON.stringify(response))); }) .catch(err => logError(eventName, err)); }; const logError = (eventName, error) => console.error("Error in: " + eventName + "\n" + error + "\n\n"); module.exports = {};
blockchain/events.js
'use strict'; const _ = require('lodash'); const fs = require('fs'); const Web3 = require('web3'); const config = require('../config'); const notifier = require('../notifications'); const userHelpers = require('../users/helpers'); const ABI = fs.readFileSync(__dirname + "/ABI.txt", "utf8").trim(); const address = fs.readFileSync(__dirname + "/contractAddress.txt", "utf8").trim(); const web3 = new Web3(); web3.setProvider(new web3.providers.HttpProvider(config.getGethUrl())); const contractInstance = web3.eth.contract(JSON.parse(ABI)).at(address); const allEvents = contractInstance.allEvents(); allEvents.watch((err, result) => { if (err) { return logError("createContractEvent", err); } console.log("Result: ", JSON.stringify(result) + "\n"); console.log("Result Args: ", JSON.stringify(result.args) + "\n"); const { eventName, message, userEthAccount } = eventResultToData(result); console.log(`Notification: ${JSON.stringify(message)} \n`); notifyUser(eventName, message, userEthAccount); }); // helper functions const eventResultToData = (eventResult) => { const eventName = eventResult.event; const argData = JSON.parse(eventResult.args.data); argData.dealId = eventResult.args.deal_id.toString(); const userEthAccount = argData.to; // eth account of person to notify const data = { info: JSON.stringify(_.omit(argData, ['to'])) }; const message = { data }; return { eventName, message, userEthAccount }; }; const notifyUser = (eventName, message, userEthAccount) => { return userHelpers.findUser({ ethAccount: userEthAccount }) .then(user => { if (!user) { return logError(eventName, Error("Cannot send notification to unknown Ethereum user account: " + userEthAccount)); } notifier.notify(user.firebaseToken, message) .then(response => console.log("Then Block: ", JSON.stringify(response))); }) .catch(err => logError(eventName, err)); }; const logError = (eventName, error) => console.error("Error in: " + eventName + "\n" + error + "\n\n"); module.exports = {};
Change notification field from `info` to `body`
blockchain/events.js
Change notification field from `info` to `body`
<ide><path>lockchain/events.js <ide> const userEthAccount = argData.to; // eth account of person to notify <ide> <ide> const data = { <del> info: JSON.stringify(_.omit(argData, ['to'])) <add> body: JSON.stringify(_.omit(argData, ['to'])) <ide> }; <ide> <ide> const message = {
Java
mit
bd2bfd0fe3557dbaf483463bbd79b99adf5aa80f
0
sk89q/CommandHelper,sk89q/CommandHelper,sk89q/CommandHelper,sk89q/CommandHelper
package com.laytonsmith.core.functions; import com.laytonsmith.PureUtilities.Version; import com.laytonsmith.abstraction.Implementation; import com.laytonsmith.abstraction.MCCommand; import com.laytonsmith.abstraction.MCCommandMap; import com.laytonsmith.abstraction.MCServer; import com.laytonsmith.abstraction.StaticLayer; import com.laytonsmith.annotations.api; import com.laytonsmith.annotations.seealso; import com.laytonsmith.core.MSVersion; import com.laytonsmith.core.Static; import com.laytonsmith.core.constructs.CArray; import com.laytonsmith.core.constructs.CBoolean; import com.laytonsmith.core.constructs.CClosure; import com.laytonsmith.core.constructs.CNull; import com.laytonsmith.core.constructs.CString; import com.laytonsmith.core.constructs.CVoid; import com.laytonsmith.core.constructs.Target; import com.laytonsmith.core.environments.CommandHelperEnvironment; import com.laytonsmith.core.environments.Environment; import com.laytonsmith.core.exceptions.CRE.CREFormatException; import com.laytonsmith.core.exceptions.CRE.CRENotFoundException; import com.laytonsmith.core.exceptions.CRE.CREThrowable; import com.laytonsmith.core.exceptions.ConfigCompileException; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.natives.interfaces.Mixed; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; /** * * @author jb_aero */ public class Commands { public static String docs() { return "A series of functions for creating and managing custom commands."; } public static Map<String, CClosure> onCommand = new HashMap<>(); public static Map<String, CClosure> onTabComplete = new HashMap<>(); @api(environments = {CommandHelperEnvironment.class}) @seealso({register_command.class}) public static class set_tabcompleter extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREFormatException.class, CRENotFoundException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { MCServer s = Static.getServer(); MCCommandMap map = s.getCommandMap(); if(map == null) { throw new CRENotFoundException(this.getName() + " is not supported in this mode (CommandMap not found).", t); } MCCommand cmd = map.getCommand(args[0].val()); if(cmd == null) { throw new CRENotFoundException("Command not found, did you forget to register it?", t); } customExec(t, environment, cmd, args[1]); return CVoid.VOID; } /** * For setting the completion code of a command that exists but might not be registered yet * * @param t * @param environment * @param cmd * @param arg */ static void customExec(Target t, Environment environment, MCCommand cmd, Mixed arg) { if(arg.isInstanceOf(CClosure.TYPE)) { onTabComplete.put(cmd.getName(), (CClosure) arg); } else { throw new CREFormatException("At this time, only closures are accepted as tabcompleters", t); } } @Override public String getName() { return "set_tabcompleter"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {commandname, closure} Sets the code that will be run when a user attempts" + " to tabcomplete a command. The closure is expected to return an array of completions," + " otherwise the tab_complete_command event will be fired and used to send completions." + " The closure is passed the following information in this order:" + " alias used, name of the sender, array of arguments used, array of command info."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Demonstrates completion suggestions for multiple arguments.", "set_tabcompleter('cmd', closure(@alias, @sender, @args, @info) {\n" + "\t@input = @args[-1];\n" + "\t@completions = array();\n" + "\tif(array_size(@args) == 1) {\n" + "\t\t@completions = array('one', 'two', 'three');\n" + "\t} else if(array_size(@args) == 2) {\n" + "\t\t@completions = array('apple', 'orange', 'banana');\n" + "\t}\n" + "\treturn(array_filter(@completions, closure(@key, @value) {\n" + "\t\treturn(length(@input) <= length(@value) \n" + "\t\t\t\t&& equals_ic(@input, substr(@value, 0, length(@input))));\n" + "\t}));\n" + "});", "Will only suggest 'orange' if given 'o' for the second argument for /cmd.") }; } } @api(environments = {CommandHelperEnvironment.class}) @seealso({register_command.class}) public static class unregister_command extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRENotFoundException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { MCCommandMap map = Static.getServer().getCommandMap(); if(map == null) { throw new CRENotFoundException(this.getName() + " is not supported in this mode (CommandMap not found).", t); } String name = args[0].val(); MCCommand cmd = map.getCommand(name); if(cmd == null) { throw new CRENotFoundException("Command not found, did you forget to register it?", t); } boolean success = map.unregister(cmd); if(success) { onCommand.remove(name); onTabComplete.remove(name); } return CBoolean.get(success); } @Override public String getName() { return "unregister_command"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "boolean {commandname} Unregisters a command from the server's command list." + " Commands from other plugins can be unregistered using this function."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api(environments = {CommandHelperEnvironment.class}) @seealso({set_tabcompleter.class, set_executor.class, unregister_command.class}) public static class register_command extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREFormatException.class, CRENotFoundException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { MCCommandMap map = Static.getServer().getCommandMap(); if(map == null) { throw new CRENotFoundException(this.getName() + " is not supported in this mode (CommandMap not found).", t); } MCCommand cmd = map.getCommand(args[0].val().toLowerCase()); String prefix = Implementation.GetServerType().getBranding().toLowerCase(Locale.ENGLISH); boolean register = false; if(cmd == null) { register = true; cmd = StaticLayer.GetConvertor().getNewCommand(args[0].val().toLowerCase()); } if(args[1].isInstanceOf(CArray.TYPE)) { CArray ops = (CArray) args[1]; if(ops.containsKey("permission")) { cmd.setPermission(ops.get("permission", t).val()); } if(ops.containsKey("description")) { cmd.setDescription(ops.get("description", t).val()); } if(ops.containsKey("usage")) { cmd.setUsage(ops.get("usage", t).val()); } if(ops.containsKey("noPermMsg")) { cmd.setPermissionMessage(ops.get("noPermMsg", t).val()); } List<String> oldAliases = new ArrayList<>(cmd.getAliases()); if(ops.containsKey("aliases")) { if(ops.get("aliases", t).isInstanceOf(CArray.TYPE)) { List<Mixed> ca = ((CArray) ops.get("aliases", t)).asList(); List<String> aliases = new ArrayList<>(); for(Mixed c : ca) { String alias = c.val().toLowerCase().trim(); if(!oldAliases.remove(alias)) { register = true; } aliases.add(alias); } cmd.setAliases(aliases); } } if(oldAliases.size() > 0) { // we need to remove these for(String alias : oldAliases) { map.unregister(prefix + ":" + alias); map.unregister(alias); } } if(ops.containsKey("executor")) { set_executor.customExec(t, environment, cmd, ops.get("executor", t)); } if(ops.containsKey("tabcompleter")) { set_tabcompleter.customExec(t, environment, cmd, ops.get("tabcompleter", t)); } boolean success = true; if(register) { cmd.unregister(map); success = map.register(prefix, cmd); } return CBoolean.get(success); } else { throw new CREFormatException("Arg 2 was expected to be an array.", t); } } @Override public String getName() { return "register_command"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "boolean {commandname, optionsArray} Registers a command to the server's command list," + " or updates an existing one. Options is an associative array that can have the following keys:" + " description, usage, permission, noPermMsg, aliases, tabcompleter, and/or executor." + " The 'noPermMsg' argument is the message displayed when the user doesn't have the permission" + " specified in 'permission'. The 'usage' is the message shown when the 'executor' returns false." + " The 'executor' is the closure run when the command is executed," + " and can return true or false (by default is treated as true). The 'tabcompleter' is the closure" + " run when a user hits tab while the command is entered and ready for args." + " It is meant to return an array of completions, but if not the tab_complete_command event" + " will be fired, and the completions of that event will be sent to the user. Both executor" + " and tabcompleter closures are passed the following information in this order:" + " alias used, name of the sender, array of arguments used, array of command info."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Register the /hug <player> command.", "register_command('hug', array(\n" + "\t'description': 'Spread the love!',\n" + "\t'usage': '/hug <player>',\n" + "\t'permission': 'perms.hugs',\n" + "\t'noPermMsg': 'You do not have permission to give hugs to players (Sorry :o).',\n" + "\t'tabcompleter':\n" + "\t\tclosure(@alias, @sender, @args) {\n" + "\t\t\t// This replicates the default tabcompleter for registered commands.\n" + "\t\t\t// If no tabcompleter is set, this behavior is used.\n" + "\t\t\t@input = @args[-1];\n" + "\t\t\treturn(array_filter(all_players(), closure(@key, @value) {\n" + "\t\t\t\treturn(length(@input) <= length(@value)\n" + "\t\t\t\t\t\t&& equals_ic(@input, substr(@value, 0, length(@input))));\n" + "\t\t\t}));\n" + "\t\t},\n" + "\t'aliases': array('hugg', 'hugs'),\n" + "\t'executor':\n" + "\t\tclosure(@alias, @sender, @args) {\n" + "\t\t\tif(array_size(@args) == 1) {\n" + "\t\t\t\t@target = @args[0];\n" + "\t\t\t\tif(ponline(@target)) {\n" + "\t\t\t\t\tbroadcast(colorize('&4'.@sender.' &6hugs &4'.@target));\n" + "\t\t\t\t} else {\n" + "\t\t\t\t\tmsg(colorize('&cThe given player is not online.'));\n" + "\t\t\t\t}\n" + "\t\t\t\treturn(true);\n" + "\t\t\t}\n" + "\t\t\treturn(false); // prints usage\n" + "\t\t}\n" + "));", "Registers the /hug command.") }; } } @api(environments = {CommandHelperEnvironment.class}) @seealso({register_command.class}) public static class set_executor extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREFormatException.class, CRENotFoundException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { MCCommandMap map = Static.getServer().getCommandMap(); if(map == null) { throw new CRENotFoundException(this.getName() + " is not supported in this mode (CommandMap not found).", t); } MCCommand cmd = map.getCommand(args[0].val()); if(cmd == null) { throw new CRENotFoundException("Command not found did you forget to register it?", t); } customExec(t, environment, cmd, args[1]); return CVoid.VOID; } /** * For setting the execution code of a command that exists but might not be registered yet * * @param t * @param environment * @param cmd * @param arg */ static void customExec(Target t, Environment environment, MCCommand cmd, Mixed arg) { if(arg.isInstanceOf(CClosure.TYPE)) { onCommand.put(cmd.getName(), (CClosure) arg); } else { throw new CREFormatException("At this time, only closures are accepted as command executors.", t); } } @Override public String getName() { return "set_executor"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {commandname, closure} Sets the code that will be run when a user attempts to execute a command." + " The closure can return true false (treated as true by default). Returning false will display" + " The usage message if it is set. The closure is passed the following information in this order:" + " alias used, name of the sender, array of arguments used, array of command info."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api(environments = {CommandHelperEnvironment.class}) public static class get_commands extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { MCCommandMap map = Static.getServer().getCommandMap(); if(map == null) { return CNull.NULL; } Collection<MCCommand> commands = map.getCommands(); CArray ret = CArray.GetAssociativeArray(t); for(MCCommand command : commands) { CArray ca = CArray.GetAssociativeArray(t); ca.set("name", new CString(command.getName(), t), t); ca.set("description", new CString(command.getDescription(), t), t); Mixed permission; if(command.getPermission() == null) { permission = CNull.NULL; } else { permission = new CString(command.getPermission(), t); } ca.set("permission", permission, t); ca.set("nopermmsg", new CString(command.getPermissionMessage(), t), t); ca.set("usage", new CString(command.getUsage(), t), t); CArray aliases = new CArray(t); for(String a : command.getAliases()) { aliases.push(new CString(a, t), t); } ca.set("aliases", aliases, t); ret.set(command.getName(), ca, t); } return ret; } @Override public String getName() { return "get_commands"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "array {} Returns an array of command arrays in the format register_command expects or null if no" + " commands could be found. The command arrays will not include executors or tabcompleters." + " This does not include " + Implementation.GetServerType().getBranding() + " aliases, as they are not registered commands."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api(environments = {CommandHelperEnvironment.class}) public static class clear_commands extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { MCCommandMap map = Static.getServer().getCommandMap(); if(map != null) { map.clearCommands(); } return CVoid.VOID; } @Override public String getName() { return "clear_commands"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "void {} Attempts to clear all registered commands on the server. Vanilla and default Spigot" + " functions are not affected, but all plugins commands are."; } @Override public Version since() { return MSVersion.V3_3_1; } } }
src/main/java/com/laytonsmith/core/functions/Commands.java
package com.laytonsmith.core.functions; import com.laytonsmith.PureUtilities.Version; import com.laytonsmith.abstraction.Implementation; import com.laytonsmith.abstraction.MCCommand; import com.laytonsmith.abstraction.MCCommandMap; import com.laytonsmith.abstraction.MCServer; import com.laytonsmith.abstraction.StaticLayer; import com.laytonsmith.annotations.api; import com.laytonsmith.annotations.seealso; import com.laytonsmith.core.MSVersion; import com.laytonsmith.core.Static; import com.laytonsmith.core.constructs.CArray; import com.laytonsmith.core.constructs.CBoolean; import com.laytonsmith.core.constructs.CClosure; import com.laytonsmith.core.constructs.CNull; import com.laytonsmith.core.constructs.CString; import com.laytonsmith.core.constructs.CVoid; import com.laytonsmith.core.constructs.Target; import com.laytonsmith.core.environments.CommandHelperEnvironment; import com.laytonsmith.core.environments.Environment; import com.laytonsmith.core.exceptions.CRE.CREFormatException; import com.laytonsmith.core.exceptions.CRE.CRENotFoundException; import com.laytonsmith.core.exceptions.CRE.CREThrowable; import com.laytonsmith.core.exceptions.ConfigCompileException; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.natives.interfaces.Mixed; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; /** * * @author jb_aero */ public class Commands { public static String docs() { return "A series of functions for creating and managing custom commands."; } public static Map<String, CClosure> onCommand = new HashMap<>(); public static Map<String, CClosure> onTabComplete = new HashMap<>(); @api(environments = {CommandHelperEnvironment.class}) @seealso({register_command.class}) public static class set_tabcompleter extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREFormatException.class, CRENotFoundException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { MCServer s = Static.getServer(); MCCommandMap map = s.getCommandMap(); if(map == null) { throw new CRENotFoundException(this.getName() + " is not supported in this mode (CommandMap not found).", t); } MCCommand cmd = map.getCommand(args[0].val()); if(cmd == null) { throw new CRENotFoundException("Command not found, did you forget to register it?", t); } customExec(t, environment, cmd, args[1]); return CVoid.VOID; } /** * For setting the completion code of a command that exists but might not be registered yet * * @param t * @param environment * @param cmd * @param arg */ static void customExec(Target t, Environment environment, MCCommand cmd, Mixed arg) { if(arg.isInstanceOf(CClosure.TYPE)) { onTabComplete.put(cmd.getName(), (CClosure) arg); } else { throw new CREFormatException("At this time, only closures are accepted as tabcompleters", t); } } @Override public String getName() { return "set_tabcompleter"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {commandname, closure} Sets the code that will be run when a user attempts" + " to tabcomplete a command. The closure is expected to return an array of completions," + " otherwise the tab_complete_command event will be fired and used to send completions." + " The closure is passed the following information in this order:" + " alias used, name of the sender, array of arguments used, array of command info."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Demonstrates completion suggestions for multiple arguments.", "set_tabcompleter('cmd', closure(@alias, @sender, @args, @info) {\n" + "\t@input = @args[-1];\n" + "\t@completions = array();\n" + "\tif(array_size(@args) == 1) {\n" + "\t\t@completions = array('one', 'two', 'three');\n" + "\t} else if(array_size(@args) == 2) {\n" + "\t\t@completions = array('apple', 'orange', 'banana');\n" + "\t}\n" + "\treturn(array_filter(@completions, closure(@key, @value) {\n" + "\t\treturn(length(@input) <= length(@value) \n" + "\t\t\t\t&& equals_ic(@input, substr(@value, 0, length(@input))));\n" + "\t}));\n" + "});", "Will only suggest 'orange' if given 'o' for the second argument for /cmd.") }; } } @api(environments = {CommandHelperEnvironment.class}) @seealso({register_command.class}) public static class unregister_command extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRENotFoundException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { MCCommandMap map = Static.getServer().getCommandMap(); if(map == null) { throw new CRENotFoundException(this.getName() + " is not supported in this mode (CommandMap not found).", t); } String name = args[0].val(); MCCommand cmd = map.getCommand(name); if(cmd == null) { throw new CRENotFoundException("Command not found, did you forget to register it?", t); } boolean success = map.unregister(cmd); if(success) { onCommand.remove(name); onTabComplete.remove(name); } return CBoolean.get(success); } @Override public String getName() { return "unregister_command"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "boolean {commandname} Unregisters a command from the server's command list." + " Commands from other plugins can be unregistered using this function."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api(environments = {CommandHelperEnvironment.class}) @seealso({set_tabcompleter.class, set_executor.class, unregister_command.class}) public static class register_command extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREFormatException.class, CRENotFoundException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { MCCommandMap map = Static.getServer().getCommandMap(); if(map == null) { throw new CRENotFoundException(this.getName() + " is not supported in this mode (CommandMap not found).", t); } MCCommand cmd = map.getCommand(args[0].val().toLowerCase()); String prefix = Implementation.GetServerType().getBranding().toLowerCase(Locale.ENGLISH); boolean register = false; if(cmd == null) { register = true; cmd = StaticLayer.GetConvertor().getNewCommand(args[0].val().toLowerCase()); } if(args[1].isInstanceOf(CArray.TYPE)) { CArray ops = (CArray) args[1]; if(ops.containsKey("permission")) { cmd.setPermission(ops.get("permission", t).val()); } if(ops.containsKey("description")) { cmd.setDescription(ops.get("description", t).val()); } if(ops.containsKey("usage")) { cmd.setUsage(ops.get("usage", t).val()); } if(ops.containsKey("noPermMsg")) { cmd.setPermissionMessage(ops.get("noPermMsg", t).val()); } List<String> oldAliases = new ArrayList<>(cmd.getAliases()); if(ops.containsKey("aliases")) { if(ops.get("aliases", t).isInstanceOf(CArray.TYPE)) { List<Mixed> ca = ((CArray) ops.get("aliases", t)).asList(); List<String> aliases = new ArrayList<>(); for(Mixed c : ca) { String alias = c.val().toLowerCase().trim(); if(!oldAliases.remove(alias)) { register = true; } aliases.add(alias); } cmd.setAliases(aliases); } } if(oldAliases.size() > 0) { // we need to remove these for(String alias : oldAliases) { map.unregister(prefix + ":" + alias); map.unregister(alias); } } if(ops.containsKey("executor")) { set_executor.customExec(t, environment, cmd, ops.get("executor", t)); } if(ops.containsKey("tabcompleter")) { set_tabcompleter.customExec(t, environment, cmd, ops.get("tabcompleter", t)); } boolean success = true; if(register) { cmd.unregister(map); success = map.register(prefix, cmd); } return CBoolean.get(success); } else { throw new CREFormatException("Arg 2 was expected to be an array.", t); } } @Override public String getName() { return "register_command"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "boolean {commandname, optionsArray} Registers a command to the server's command list," + " or updates an existing one. Options is an associative array that can have the following keys:" + " description, usage, permission, noPermMsg, aliases, tabcompleter, and/or executor." + " The 'noPermMsg' argument is the message displayed when the user doesn't have the permission" + " specified in 'permission'. The 'usage' is the message shown when the 'executor' returns false." + " The 'executor' is the closure run when the command is executed," + " and can return true or false (by default is treated as true). The 'tabcompleter' is the closure" + " run when a user hits tab while the command is entered and ready for args." + " It is meant to return an array of completions, but if not the tab_complete_command event" + " will be fired, and the completions of that event will be sent to the user. Both executor" + " and tabcompleter closures are passed the following information in this order:" + " alias used, name of the sender, array of arguments used, array of command info."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Register the /hug <player> command.", "register_command('hug', array(\n" + "\t'description': 'Spread the love!',\n" + "\t'usage': '/hug <player>',\n" + "\t'permission': 'perms.hugs',\n" + "\t'noPermMsg': 'You do not have permission to give hugs to players (Sorry :o).',\n" + "\t'tabcompleter':\n" + "\t\tclosure(@alias, @sender, @args) {\n" + "\t\t\t// This replicates the default tabcompleter for registered commands." + "\t\t\t// If no tabcompleter is set, this behavior is used." + "\t\t\t@input = @args[-1];\n" + "\t\t\treturn(array_filter(all_players(), closure(@key, @value) {\n" + "\t\t\t\treturn(length(@input) <= length(@value)\n" + "\t\t\t\t\t\t&& equals_ic(@input, substr(@value, 0, length(@input))));\n" + "\t\t\t}));\n" + "\t\t},\n" + "\t'aliases': array('hugg', 'hugs'),\n" + "\t'executor':\n" + "\t\tclosure(@alias, @sender, @args) {\n" + "\t\t\tif(array_size(@args) == 1) {\n" + "\t\t\t\t@target = @args[0];" + "\t\t\t\tif(ponline(@target)) {\n" + "\t\t\t\t\tbroadcast(colorize('&4'.@sender.' &6hugs &4'.@target));\n" + "\t\t\t\t} else {\n" + "\t\t\t\t\tmsg(colorize('&cThe given player is not online.'));\n" + "\t\t\t\t}\n" + "\t\t\t\treturn(true);\n" + "\t\t\t}\n" + "\t\t\treturn(false); // prints usage\n" + "\t\t}\n" + "));", "Registers the /hug command.") }; } } @api(environments = {CommandHelperEnvironment.class}) @seealso({register_command.class}) public static class set_executor extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREFormatException.class, CRENotFoundException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { MCCommandMap map = Static.getServer().getCommandMap(); if(map == null) { throw new CRENotFoundException(this.getName() + " is not supported in this mode (CommandMap not found).", t); } MCCommand cmd = map.getCommand(args[0].val()); if(cmd == null) { throw new CRENotFoundException("Command not found did you forget to register it?", t); } customExec(t, environment, cmd, args[1]); return CVoid.VOID; } /** * For setting the execution code of a command that exists but might not be registered yet * * @param t * @param environment * @param cmd * @param arg */ static void customExec(Target t, Environment environment, MCCommand cmd, Mixed arg) { if(arg.isInstanceOf(CClosure.TYPE)) { onCommand.put(cmd.getName(), (CClosure) arg); } else { throw new CREFormatException("At this time, only closures are accepted as command executors.", t); } } @Override public String getName() { return "set_executor"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {commandname, closure} Sets the code that will be run when a user attempts to execute a command." + " The closure can return true false (treated as true by default). Returning false will display" + " The usage message if it is set. The closure is passed the following information in this order:" + " alias used, name of the sender, array of arguments used, array of command info."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api(environments = {CommandHelperEnvironment.class}) public static class get_commands extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { MCCommandMap map = Static.getServer().getCommandMap(); if(map == null) { return CNull.NULL; } Collection<MCCommand> commands = map.getCommands(); CArray ret = CArray.GetAssociativeArray(t); for(MCCommand command : commands) { CArray ca = CArray.GetAssociativeArray(t); ca.set("name", new CString(command.getName(), t), t); ca.set("description", new CString(command.getDescription(), t), t); Mixed permission; if(command.getPermission() == null) { permission = CNull.NULL; } else { permission = new CString(command.getPermission(), t); } ca.set("permission", permission, t); ca.set("nopermmsg", new CString(command.getPermissionMessage(), t), t); ca.set("usage", new CString(command.getUsage(), t), t); CArray aliases = new CArray(t); for(String a : command.getAliases()) { aliases.push(new CString(a, t), t); } ca.set("aliases", aliases, t); ret.set(command.getName(), ca, t); } return ret; } @Override public String getName() { return "get_commands"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "array {} Returns an array of command arrays in the format register_command expects or null if no" + " commands could be found. The command arrays will not include executors or tabcompleters." + " This does not include " + Implementation.GetServerType().getBranding() + " aliases, as they are not registered commands."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api(environments = {CommandHelperEnvironment.class}) public static class clear_commands extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { MCCommandMap map = Static.getServer().getCommandMap(); if(map != null) { map.clearCommands(); } return CVoid.VOID; } @Override public String getName() { return "clear_commands"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "void {} Attempts to clear all registered commands on the server. Vanilla and default Spigot" + " functions are not affected, but all plugins commands are."; } @Override public Version since() { return MSVersion.V3_3_1; } } }
Fix missing newlines in register_command example
src/main/java/com/laytonsmith/core/functions/Commands.java
Fix missing newlines in register_command example
<ide><path>rc/main/java/com/laytonsmith/core/functions/Commands.java <ide> + "\t'noPermMsg': 'You do not have permission to give hugs to players (Sorry :o).',\n" <ide> + "\t'tabcompleter':\n" <ide> + "\t\tclosure(@alias, @sender, @args) {\n" <del> + "\t\t\t// This replicates the default tabcompleter for registered commands." <del> + "\t\t\t// If no tabcompleter is set, this behavior is used." <add> + "\t\t\t// This replicates the default tabcompleter for registered commands.\n" <add> + "\t\t\t// If no tabcompleter is set, this behavior is used.\n" <ide> + "\t\t\t@input = @args[-1];\n" <ide> + "\t\t\treturn(array_filter(all_players(), closure(@key, @value) {\n" <ide> + "\t\t\t\treturn(length(@input) <= length(@value)\n" <ide> + "\t'executor':\n" <ide> + "\t\tclosure(@alias, @sender, @args) {\n" <ide> + "\t\t\tif(array_size(@args) == 1) {\n" <del> + "\t\t\t\t@target = @args[0];" <add> + "\t\t\t\t@target = @args[0];\n" <ide> + "\t\t\t\tif(ponline(@target)) {\n" <ide> + "\t\t\t\t\tbroadcast(colorize('&4'.@sender.' &6hugs &4'.@target));\n" <ide> + "\t\t\t\t} else {\n"
Java
apache-2.0
9fc5cca663db94577a579a40cc8fac3758898eba
0
liquidm/druid,se7entyse7en/druid,nishantmonu51/druid,noddi/druid,pjain1/druid,zhaown/druid,guobingkun/druid,OttoOps/druid,dkhwangbo/druid,knoguchi/druid,kevintvh/druid,monetate/druid,solimant/druid,jon-wei/druid,guobingkun/druid,authbox-lib/druid,calliope7/druid,haoch/druid,optimizely/druid,dclim/druid,authbox-lib/druid,himanshug/druid,zhihuij/druid,Deebs21/druid,cocosli/druid,himanshug/druid,rasahner/druid,milimetric/druid,potto007/druid-avro,pjain1/druid,fjy/druid,gianm/druid,calliope7/druid,penuel-leo/druid,elijah513/druid,Kleagleguo/druid,Kleagleguo/druid,erikdubbelboer/druid,implydata/druid,jon-wei/druid,friedhardware/druid,nvoron23/druid,zxs/druid,b-slim/druid,nishantmonu51/druid,pdeva/druid,authbox-lib/druid,michaelschiff/druid,tubemogul/druid,redBorder/druid,monetate/druid,taochaoqiang/druid,noddi/druid,wenjixin/druid,friedhardware/druid,zhihuij/druid,liquidm/druid,eshen1991/druid,optimizely/druid,zxs/druid,gianm/druid,friedhardware/druid,b-slim/druid,Deebs21/druid,zhihuij/druid,pdeva/druid,lcp0578/druid,monetate/druid,tubemogul/druid,zengzhihai110/druid,potto007/druid-avro,kevintvh/druid,mrijke/druid,Deebs21/druid,cocosli/druid,lizhanhui/data_druid,skyportsystems/druid,lcp0578/druid,mghosh4/druid,optimizely/druid,lizhanhui/data_druid,andy256/druid,monetate/druid,deltaprojects/druid,druid-io/druid,michaelschiff/druid,eshen1991/druid,minewhat/druid,Kleagleguo/druid,milimetric/druid,dkhwangbo/druid,erikdubbelboer/druid,haoch/druid,zhiqinghuang/druid,nvoron23/druid,rasahner/druid,se7entyse7en/druid,taochaoqiang/druid,guobingkun/druid,dclim/druid,himanshug/druid,du00cs/druid,premc/druid,monetate/druid,skyportsystems/druid,nishantmonu51/druid,wenjixin/druid,premc/druid,amikey/druid,b-slim/druid,solimant/druid,nvoron23/druid,se7entyse7en/druid,se7entyse7en/druid,rasahner/druid,yaochitc/druid-dev,mangeshpardeshiyahoo/druid,skyportsystems/druid,cocosli/druid,minewhat/druid,guobingkun/druid,michaelschiff/druid,amikey/druid,penuel-leo/druid,mghosh4/druid,anupkumardixit/druid,yaochitc/druid-dev,lizhanhui/data_druid,michaelschiff/druid,KurtYoung/druid,elijah513/druid,lizhanhui/data_druid,gianm/druid,monetate/druid,calliope7/druid,lizhanhui/data_druid,OttoOps/druid,tubemogul/druid,praveev/druid,pombredanne/druid,yaochitc/druid-dev,mrijke/druid,minewhat/druid,noddi/druid,metamx/druid,praveev/druid,penuel-leo/druid,redBorder/druid,zengzhihai110/druid,druid-io/druid,nishantmonu51/druid,himanshug/druid,Kleagleguo/druid,anupkumardixit/druid,se7entyse7en/druid,nishantmonu51/druid,authbox-lib/druid,jon-wei/druid,solimant/druid,deltaprojects/druid,praveev/druid,redBorder/druid,767326791/druid,pombredanne/druid,redBorder/druid,druid-io/druid,Fokko/druid,elijah513/druid,smartpcr/druid,dkhwangbo/druid,mangeshpardeshiyahoo/druid,andy256/druid,implydata/druid,mghosh4/druid,b-slim/druid,wenjixin/druid,milimetric/druid,potto007/druid-avro,dclim/druid,jon-wei/druid,767326791/druid,eshen1991/druid,pjain1/druid,mangeshpardeshiyahoo/druid,implydata/druid,smartpcr/druid,fjy/druid,qix/druid,nishantmonu51/druid,KurtYoung/druid,tubemogul/druid,pombredanne/druid,dclim/druid,767326791/druid,friedhardware/druid,jon-wei/druid,Kleagleguo/druid,authbox-lib/druid,b-slim/druid,calliope7/druid,liquidm/druid,knoguchi/druid,leventov/druid,smartpcr/druid,rasahner/druid,penuel-leo/druid,pjain1/druid,winval/druid,zxs/druid,zhihuij/druid,lcp0578/druid,yaochitc/druid-dev,himanshug/druid,KurtYoung/druid,mghosh4/druid,mghosh4/druid,Fokko/druid,calliope7/druid,kevintvh/druid,anupkumardixit/druid,zhiqinghuang/druid,michaelschiff/druid,dkhwangbo/druid,elijah513/druid,winval/druid,dclim/druid,metamx/druid,yaochitc/druid-dev,erikdubbelboer/druid,zxs/druid,leventov/druid,zhaown/druid,solimant/druid,liquidm/druid,zengzhihai110/druid,mrijke/druid,gianm/druid,elijah513/druid,nvoron23/druid,fjy/druid,amikey/druid,dkhwangbo/druid,lcp0578/druid,Fokko/druid,friedhardware/druid,eshen1991/druid,premc/druid,implydata/druid,fjy/druid,haoch/druid,767326791/druid,du00cs/druid,du00cs/druid,deltaprojects/druid,zhaown/druid,pjain1/druid,KurtYoung/druid,OttoOps/druid,penuel-leo/druid,anupkumardixit/druid,taochaoqiang/druid,metamx/druid,haoch/druid,minewhat/druid,zhiqinghuang/druid,kevintvh/druid,anupkumardixit/druid,metamx/druid,kevintvh/druid,zxs/druid,Fokko/druid,zhaown/druid,potto007/druid-avro,winval/druid,Fokko/druid,erikdubbelboer/druid,pombredanne/druid,pjain1/druid,zhaown/druid,pdeva/druid,skyportsystems/druid,praveev/druid,zhiqinghuang/druid,liquidm/druid,fjy/druid,implydata/druid,liquidm/druid,cocosli/druid,nvoron23/druid,premc/druid,Deebs21/druid,zhihuij/druid,pdeva/druid,leventov/druid,deltaprojects/druid,rasahner/druid,leventov/druid,OttoOps/druid,metamx/druid,Fokko/druid,jon-wei/druid,pdeva/druid,haoch/druid,767326791/druid,mghosh4/druid,andy256/druid,skyportsystems/druid,knoguchi/druid,nishantmonu51/druid,mangeshpardeshiyahoo/druid,mghosh4/druid,qix/druid,du00cs/druid,wenjixin/druid,deltaprojects/druid,pombredanne/druid,minewhat/druid,potto007/druid-avro,andy256/druid,andy256/druid,wenjixin/druid,druid-io/druid,du00cs/druid,qix/druid,milimetric/druid,optimizely/druid,qix/druid,milimetric/druid,winval/druid,michaelschiff/druid,zengzhihai110/druid,pjain1/druid,zhiqinghuang/druid,smartpcr/druid,OttoOps/druid,gianm/druid,mrijke/druid,erikdubbelboer/druid,deltaprojects/druid,taochaoqiang/druid,jon-wei/druid,smartpcr/druid,cocosli/druid,mangeshpardeshiyahoo/druid,KurtYoung/druid,taochaoqiang/druid,noddi/druid,gianm/druid,deltaprojects/druid,tubemogul/druid,amikey/druid,redBorder/druid,mrijke/druid,qix/druid,amikey/druid,Fokko/druid,Deebs21/druid,noddi/druid,premc/druid,implydata/druid,druid-io/druid,eshen1991/druid,optimizely/druid,zengzhihai110/druid,lcp0578/druid,winval/druid,michaelschiff/druid,guobingkun/druid,monetate/druid,praveev/druid,solimant/druid,knoguchi/druid,leventov/druid,gianm/druid,knoguchi/druid
/* * Druid - a distributed column store. * Copyright (C) 2012, 2013, 2014 Metamarkets Group Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package io.druid.client; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.dataformat.smile.SmileFactory; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; import com.metamx.common.ISE; import com.metamx.common.guava.FunctionalIterable; import com.metamx.common.guava.MergeIterable; import com.metamx.common.guava.Sequence; import com.metamx.common.guava.Sequences; import com.metamx.common.guava.nary.TrinaryFn; import io.druid.query.topn.TopNQuery; import io.druid.query.topn.TopNQueryBuilder; import io.druid.query.topn.TopNQueryConfig; import io.druid.query.topn.TopNQueryQueryToolChest; import io.druid.query.topn.TopNResultValue; import io.druid.client.cache.Cache; import io.druid.client.cache.MapCache; import io.druid.client.selector.QueryableDruidServer; import io.druid.client.selector.RandomServerSelectorStrategy; import io.druid.client.selector.ServerSelector; import io.druid.granularity.PeriodGranularity; import io.druid.granularity.QueryGranularity; import io.druid.jackson.DefaultObjectMapper; import io.druid.query.BySegmentResultValueClass; import io.druid.query.Druids; import io.druid.query.MapQueryToolChestWarehouse; import io.druid.query.Query; import io.druid.query.QueryConfig; import io.druid.query.QueryRunner; import io.druid.query.QueryToolChest; import io.druid.query.Result; import io.druid.query.SegmentDescriptor; import io.druid.query.aggregation.AggregatorFactory; import io.druid.query.aggregation.CountAggregatorFactory; import io.druid.query.aggregation.LongSumAggregatorFactory; import io.druid.query.aggregation.PostAggregator; import io.druid.query.aggregation.post.ArithmeticPostAggregator; import io.druid.query.aggregation.post.FieldAccessPostAggregator; import io.druid.query.filter.DimFilter; import io.druid.query.search.SearchQueryQueryToolChest; import io.druid.query.search.SearchResultValue; import io.druid.query.search.search.InsensitiveContainsSearchQuerySpec; import io.druid.query.search.search.SearchHit; import io.druid.query.search.search.SearchQuery; import io.druid.query.search.search.SearchQueryConfig; import io.druid.query.spec.MultipleIntervalSegmentSpec; import io.druid.query.timeboundary.TimeBoundaryQuery; import io.druid.query.timeboundary.TimeBoundaryResultValue; import io.druid.query.timeseries.TimeseriesQuery; import io.druid.query.timeseries.TimeseriesQueryQueryToolChest; import io.druid.query.timeseries.TimeseriesResultValue; import io.druid.segment.TestHelper; import io.druid.timeline.DataSegment; import io.druid.timeline.VersionedIntervalTimeline; import io.druid.timeline.partition.NoneShardSpec; import io.druid.timeline.partition.PartitionChunk; import io.druid.timeline.partition.ShardSpec; import io.druid.timeline.partition.SingleElementPartitionChunk; import io.druid.timeline.partition.StringPartitionChunk; import org.easymock.Capture; import org.easymock.EasyMock; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Interval; import org.joda.time.Period; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import javax.annotation.Nullable; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.TreeMap; import java.util.concurrent.Executor; /** */ @RunWith(Parameterized.class) public class CachingClusteredClientTest { /** * We want a deterministic test, but we'd also like a bit of randomness for the distribution of segments * across servers. Thus, we loop multiple times and each time use a deterministically created Random instance. * Increase this value to increase exposure to random situations at the expense of test run time. */ private static final int RANDOMNESS = 10; public static final ImmutableMap<String, String> CONTEXT = ImmutableMap.of(); public static final MultipleIntervalSegmentSpec SEG_SPEC = new MultipleIntervalSegmentSpec(ImmutableList.<Interval>of()); public static final String DATA_SOURCE = "test"; private static final List<AggregatorFactory> AGGS = Arrays.asList( new CountAggregatorFactory("rows"), new LongSumAggregatorFactory("imps", "imps"), new LongSumAggregatorFactory("impers", "imps") ); private static final List<PostAggregator> POST_AGGS = Arrays.<PostAggregator>asList( new ArithmeticPostAggregator( "avg_imps_per_row", "/", Arrays.<PostAggregator>asList( new FieldAccessPostAggregator("imps", "imps"), new FieldAccessPostAggregator("rows", "rows") ) ) ); private static final List<AggregatorFactory> RENAMED_AGGS = Arrays.asList( new CountAggregatorFactory("rows2"), new LongSumAggregatorFactory("imps", "imps"), new LongSumAggregatorFactory("impers2", "imps") ); private static final DimFilter DIM_FILTER = null; private static final List<PostAggregator> RENAMED_POST_AGGS = Arrays.asList(); private static final QueryGranularity GRANULARITY = QueryGranularity.DAY; private static final DateTimeZone TIMEZONE = DateTimeZone.forID("America/Los_Angeles"); private static final QueryGranularity PT1H_TZ_GRANULARITY = new PeriodGranularity(new Period("PT1H"), null, TIMEZONE); private static final String TOP_DIM = "a_dim"; @Parameterized.Parameters public static Collection<?> constructorFeeder() throws IOException { return Lists.transform( Lists.newArrayList(new RangeIterable(RANDOMNESS)), new Function<Integer, Object>() { @Override public Object apply(@Nullable Integer input) { return new Object[]{input}; } } ); } protected static final DefaultObjectMapper jsonMapper = new DefaultObjectMapper(new SmileFactory()); static { jsonMapper.getFactory().setCodec(jsonMapper); } private final Random random; protected VersionedIntervalTimeline<String, ServerSelector> timeline; protected TimelineServerView serverView; protected Cache cache; CachingClusteredClient client; DruidServer[] servers; public CachingClusteredClientTest(int randomSeed) { this.random = new Random(randomSeed); } @Before public void setUp() throws Exception { timeline = new VersionedIntervalTimeline<>(Ordering.<String>natural()); serverView = EasyMock.createStrictMock(TimelineServerView.class); cache = MapCache.create(100000); client = makeClient(); servers = new DruidServer[]{ new DruidServer("test1", "test1", 10, "historical", "bye", 0), new DruidServer("test2", "test2", 10, "historical", "bye", 0), new DruidServer("test3", "test3", 10, "historical", "bye", 0), new DruidServer("test4", "test4", 10, "historical", "bye", 0), new DruidServer("test5", "test5", 10, "historical", "bye", 0) }; } @Test @SuppressWarnings("unchecked") public void testTimeseriesCaching() throws Exception { final Druids.TimeseriesQueryBuilder builder = Druids.newTimeseriesQueryBuilder() .dataSource(DATA_SOURCE) .intervals(SEG_SPEC) .filters(DIM_FILTER) .granularity(GRANULARITY) .aggregators(AGGS) .postAggregators(POST_AGGS) .context(CONTEXT); testQueryCaching( builder.build(), new Interval("2011-01-01/2011-01-02"), makeTimeResults(new DateTime("2011-01-01"), 50, 5000), new Interval("2011-01-02/2011-01-03"), makeTimeResults(new DateTime("2011-01-02"), 30, 6000), new Interval("2011-01-04/2011-01-05"), makeTimeResults(new DateTime("2011-01-04"), 23, 85312), new Interval("2011-01-05/2011-01-10"), makeTimeResults( new DateTime("2011-01-05"), 85, 102, new DateTime("2011-01-06"), 412, 521, new DateTime("2011-01-07"), 122, 21894, new DateTime("2011-01-08"), 5, 20, new DateTime("2011-01-09"), 18, 521 ), new Interval("2011-01-05/2011-01-10"), makeTimeResults( new DateTime("2011-01-05T01"), 80, 100, new DateTime("2011-01-06T01"), 420, 520, new DateTime("2011-01-07T01"), 12, 2194, new DateTime("2011-01-08T01"), 59, 201, new DateTime("2011-01-09T01"), 181, 52 ) ); TestHelper.assertExpectedResults( makeRenamedTimeResults( new DateTime("2011-01-01"), 50, 5000, new DateTime("2011-01-02"), 30, 6000, new DateTime("2011-01-04"), 23, 85312, new DateTime("2011-01-05"), 85, 102, new DateTime("2011-01-05T01"), 80, 100, new DateTime("2011-01-06"), 412, 521, new DateTime("2011-01-06T01"), 420, 520, new DateTime("2011-01-07"), 122, 21894, new DateTime("2011-01-07T01"), 12, 2194, new DateTime("2011-01-08"), 5, 20, new DateTime("2011-01-08T01"), 59, 201, new DateTime("2011-01-09"), 18, 521, new DateTime("2011-01-09T01"), 181, 52 ), client.run( builder.intervals("2011-01-01/2011-01-10") .aggregators(RENAMED_AGGS) .postAggregators(RENAMED_POST_AGGS) .build() ) ); } @Test @SuppressWarnings("unchecked") public void testTimeseriesCachingTimeZone() throws Exception { final Druids.TimeseriesQueryBuilder builder = Druids.newTimeseriesQueryBuilder() .dataSource(DATA_SOURCE) .intervals(SEG_SPEC) .filters(DIM_FILTER) .granularity(PT1H_TZ_GRANULARITY) .aggregators(AGGS) .postAggregators(POST_AGGS) .context(CONTEXT); testQueryCaching( builder.build(), new Interval("2011-11-04/2011-11-08"), makeTimeResults( new DateTime("2011-11-04", TIMEZONE), 50, 5000, new DateTime("2011-11-05", TIMEZONE), 30, 6000, new DateTime("2011-11-06", TIMEZONE), 23, 85312, new DateTime("2011-11-07", TIMEZONE), 85, 102 ) ); TestHelper.assertExpectedResults( makeRenamedTimeResults( new DateTime("2011-11-04", TIMEZONE), 50, 5000, new DateTime("2011-11-05", TIMEZONE), 30, 6000, new DateTime("2011-11-06", TIMEZONE), 23, 85312, new DateTime("2011-11-07", TIMEZONE), 85, 102 ), client.run( builder.intervals("2011-11-04/2011-11-08") .aggregators(RENAMED_AGGS) .postAggregators(RENAMED_POST_AGGS) .build() ) ); } @Test public void testDisableUseCache() throws Exception { final Druids.TimeseriesQueryBuilder builder = Druids.newTimeseriesQueryBuilder() .dataSource(DATA_SOURCE) .intervals(SEG_SPEC) .filters(DIM_FILTER) .granularity(GRANULARITY) .aggregators(AGGS) .postAggregators(POST_AGGS); testQueryCaching( 1, true, builder.context(ImmutableMap.of("useCache", "false", "populateCache", "true")).build(), new Interval("2011-01-01/2011-01-02"), makeTimeResults(new DateTime("2011-01-01"), 50, 5000) ); Assert.assertEquals(1, cache.getStats().getNumEntries()); Assert.assertEquals(0, cache.getStats().getNumHits()); Assert.assertEquals(0, cache.getStats().getNumMisses()); cache.close("0_0"); testQueryCaching( 1, false, builder.context(ImmutableMap.of("useCache", "false", "populateCache", "false")).build(), new Interval("2011-01-01/2011-01-02"), makeTimeResults(new DateTime("2011-01-01"), 50, 5000) ); Assert.assertEquals(0, cache.getStats().getNumEntries()); Assert.assertEquals(0, cache.getStats().getNumHits()); Assert.assertEquals(0, cache.getStats().getNumMisses()); testQueryCaching( 1, false, builder.context(ImmutableMap.of("useCache", "true", "populateCache", "false")).build(), new Interval("2011-01-01/2011-01-02"), makeTimeResults(new DateTime("2011-01-01"), 50, 5000) ); Assert.assertEquals(0, cache.getStats().getNumEntries()); Assert.assertEquals(0, cache.getStats().getNumHits()); Assert.assertEquals(1, cache.getStats().getNumMisses()); } @Test @SuppressWarnings("unchecked") public void testTopNCaching() throws Exception { final TopNQueryBuilder builder = new TopNQueryBuilder() .dataSource(DATA_SOURCE) .dimension(TOP_DIM) .metric("imps") .threshold(3) .intervals(SEG_SPEC) .filters(DIM_FILTER) .granularity(GRANULARITY) .aggregators(AGGS) .postAggregators(POST_AGGS) .context(CONTEXT); testQueryCaching( builder.build(), new Interval("2011-01-01/2011-01-02"), makeTopNResults(new DateTime("2011-01-01"), "a", 50, 5000, "b", 50, 4999, "c", 50, 4998), new Interval("2011-01-02/2011-01-03"), makeTopNResults(new DateTime("2011-01-02"), "a", 50, 4997, "b", 50, 4996, "c", 50, 4995), new Interval("2011-01-05/2011-01-10"), makeTopNResults( new DateTime("2011-01-05"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-06"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-08"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-09"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983 ), new Interval("2011-01-05/2011-01-10"), makeTopNResults( new DateTime("2011-01-05T01"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-06T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-08T01"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-09T01"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983 ) ); TestHelper.assertExpectedResults( makeRenamedTopNResults( new DateTime("2011-01-01"), "a", 50, 5000, "b", 50, 4999, "c", 50, 4998, new DateTime("2011-01-02"), "a", 50, 4997, "b", 50, 4996, "c", 50, 4995, new DateTime("2011-01-05"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-05T01"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-06"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-06T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-08"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-08T01"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-09"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983, new DateTime("2011-01-09T01"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983 ), client.run( builder.intervals("2011-01-01/2011-01-10") .metric("imps") .aggregators(RENAMED_AGGS) .postAggregators(RENAMED_POST_AGGS) .build() ) ); } @Test @SuppressWarnings("unchecked") public void testTopNCachingTimeZone() throws Exception { final TopNQueryBuilder builder = new TopNQueryBuilder() .dataSource(DATA_SOURCE) .dimension(TOP_DIM) .metric("imps") .threshold(3) .intervals(SEG_SPEC) .filters(DIM_FILTER) .granularity(PT1H_TZ_GRANULARITY) .aggregators(AGGS) .postAggregators(POST_AGGS) .context(CONTEXT); testQueryCaching( builder.build(), new Interval("2011-11-04/2011-11-08"), makeTopNResults( new DateTime("2011-11-04", TIMEZONE), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-11-05", TIMEZONE), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-11-06", TIMEZONE), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-11-07", TIMEZONE), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986 ) ); TestHelper.assertExpectedResults( makeRenamedTopNResults( new DateTime("2011-11-04", TIMEZONE), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-11-05", TIMEZONE), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-11-06", TIMEZONE), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-11-07", TIMEZONE), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986 ), client.run( builder.intervals("2011-11-04/2011-11-08") .metric("imps") .aggregators(RENAMED_AGGS) .postAggregators(RENAMED_POST_AGGS) .build() ) ); } @Test @SuppressWarnings("unchecked") public void testTopNCachingEmptyResults() throws Exception { final TopNQueryBuilder builder = new TopNQueryBuilder() .dataSource(DATA_SOURCE) .dimension(TOP_DIM) .metric("imps") .threshold(3) .intervals(SEG_SPEC) .filters(DIM_FILTER) .granularity(GRANULARITY) .aggregators(AGGS) .postAggregators(POST_AGGS) .context(CONTEXT); testQueryCaching( builder.build(), new Interval("2011-01-01/2011-01-02"), makeTopNResults(), new Interval("2011-01-02/2011-01-03"), makeTopNResults(), new Interval("2011-01-05/2011-01-10"), makeTopNResults( new DateTime("2011-01-05"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-06"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-08"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-09"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983 ), new Interval("2011-01-05/2011-01-10"), makeTopNResults( new DateTime("2011-01-05T01"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-06T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-08T01"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-09T01"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983 ) ); TestHelper.assertExpectedResults( makeRenamedTopNResults( new DateTime("2011-01-05"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-05T01"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-06"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-06T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-08"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-08T01"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-09"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983, new DateTime("2011-01-09T01"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983 ), client.run( builder.intervals("2011-01-01/2011-01-10") .metric("imps") .aggregators(RENAMED_AGGS) .postAggregators(RENAMED_POST_AGGS) .build() ) ); } @Test public void testSearchCaching() throws Exception { testQueryCaching( new SearchQuery( DATA_SOURCE, DIM_FILTER, GRANULARITY, 1000, SEG_SPEC, Arrays.asList("a_dim"), new InsensitiveContainsSearchQuerySpec("how"), null, CONTEXT ), new Interval("2011-01-01/2011-01-02"), makeSearchResults(new DateTime("2011-01-01"), "how", "howdy", "howwwwww", "howwy"), new Interval("2011-01-02/2011-01-03"), makeSearchResults(new DateTime("2011-01-02"), "how1", "howdy1", "howwwwww1", "howwy1"), new Interval("2011-01-05/2011-01-10"), makeSearchResults( new DateTime("2011-01-05"), "how2", "howdy2", "howwwwww2", "howww2", new DateTime("2011-01-06"), "how3", "howdy3", "howwwwww3", "howww3", new DateTime("2011-01-07"), "how4", "howdy4", "howwwwww4", "howww4", new DateTime("2011-01-08"), "how5", "howdy5", "howwwwww5", "howww5", new DateTime("2011-01-09"), "how6", "howdy6", "howwwwww6", "howww6" ), new Interval("2011-01-05/2011-01-10"), makeSearchResults( new DateTime("2011-01-05T01"), "how2", "howdy2", "howwwwww2", "howww2", new DateTime("2011-01-06T01"), "how3", "howdy3", "howwwwww3", "howww3", new DateTime("2011-01-07T01"), "how4", "howdy4", "howwwwww4", "howww4", new DateTime("2011-01-08T01"), "how5", "howdy5", "howwwwww5", "howww5", new DateTime("2011-01-09T01"), "how6", "howdy6", "howwwwww6", "howww6" ) ); } public void testQueryCaching(final Query query, Object... args) { testQueryCaching(3, true, query, args); } @SuppressWarnings("unchecked") public void testQueryCaching( final int numTimesToQuery, boolean expectBySegment, final Query query, Object... args // does this assume query intervals must be ordered? ) { if (args.length % 2 != 0) { throw new ISE("args.length must be divisible by two, was %d", args.length); } final List<Interval> queryIntervals = Lists.newArrayListWithCapacity(args.length / 2); final List<List<Iterable<Result<Object>>>> expectedResults = Lists.newArrayListWithCapacity(queryIntervals.size()); for (int i = 0; i < args.length; i += 2) { final Interval interval = (Interval) args[i]; final Iterable<Result<Object>> results = (Iterable<Result<Object>>) args[i + 1]; if (queryIntervals.size() > 0 && interval.equals(queryIntervals.get(queryIntervals.size() - 1))) { expectedResults.get(expectedResults.size() - 1).add(results); } else { queryIntervals.add(interval); expectedResults.add(Lists.<Iterable<Result<Object>>>newArrayList(results)); } } for (int i = 0; i < queryIntervals.size(); ++i) { List<Object> mocks = Lists.newArrayList(); mocks.add(serverView); final Interval actualQueryInterval = new Interval( queryIntervals.get(0).getStart(), queryIntervals.get(i).getEnd() ); final List<Map<DruidServer, ServerExpectations>> serverExpectationList = populateTimeline( queryIntervals, expectedResults, i, mocks ); List<Capture> queryCaptures = Lists.newArrayList(); final Map<DruidServer, ServerExpectations> finalExpectation = serverExpectationList.get( serverExpectationList.size() - 1 ); for (Map.Entry<DruidServer, ServerExpectations> entry : finalExpectation.entrySet()) { DruidServer server = entry.getKey(); ServerExpectations expectations = entry.getValue(); EasyMock.expect(serverView.getQueryRunner(server)) .andReturn(expectations.getQueryRunner()) .once(); final Capture<? extends Query> capture = new Capture(); queryCaptures.add(capture); QueryRunner queryable = expectations.getQueryRunner(); if (query instanceof TimeseriesQuery) { List<String> segmentIds = Lists.newArrayList(); List<Interval> intervals = Lists.newArrayList(); List<Iterable<Result<TimeseriesResultValue>>> results = Lists.newArrayList(); for (ServerExpectation expectation : expectations) { segmentIds.add(expectation.getSegmentId()); intervals.add(expectation.getInterval()); results.add(expectation.getResults()); } EasyMock.expect(queryable.run(EasyMock.capture(capture))) .andReturn(toQueryableTimeseriesResults(expectBySegment, segmentIds, intervals, results)) .once(); } else if (query instanceof TopNQuery) { List<String> segmentIds = Lists.newArrayList(); List<Interval> intervals = Lists.newArrayList(); List<Iterable<Result<TopNResultValue>>> results = Lists.newArrayList(); for (ServerExpectation expectation : expectations) { segmentIds.add(expectation.getSegmentId()); intervals.add(expectation.getInterval()); results.add(expectation.getResults()); } EasyMock.expect(queryable.run(EasyMock.capture(capture))) .andReturn(toQueryableTopNResults(segmentIds, intervals, results)) .once(); } else if (query instanceof SearchQuery) { List<String> segmentIds = Lists.newArrayList(); List<Interval> intervals = Lists.newArrayList(); List<Iterable<Result<SearchResultValue>>> results = Lists.newArrayList(); for (ServerExpectation expectation : expectations) { segmentIds.add(expectation.getSegmentId()); intervals.add(expectation.getInterval()); results.add(expectation.getResults()); } EasyMock.expect(queryable.run(EasyMock.capture(capture))) .andReturn(toQueryableSearchResults(segmentIds, intervals, results)) .once(); } else if (query instanceof TimeBoundaryQuery) { List<String> segmentIds = Lists.newArrayList(); List<Interval> intervals = Lists.newArrayList(); List<Iterable<Result<TimeBoundaryResultValue>>> results = Lists.newArrayList(); for (ServerExpectation expectation : expectations) { segmentIds.add(expectation.getSegmentId()); intervals.add(expectation.getInterval()); results.add(expectation.getResults()); } EasyMock.expect(queryable.run(EasyMock.capture(capture))) .andReturn(toQueryableTimeBoundaryResults(segmentIds, intervals, results)) .once(); } else { throw new ISE("Unknown query type[%s]", query.getClass()); } } final int expectedResultsRangeStart; final int expectedResultsRangeEnd; if (query instanceof TimeBoundaryQuery) { expectedResultsRangeStart = i; expectedResultsRangeEnd = i + 1; } else { expectedResultsRangeStart = 0; expectedResultsRangeEnd = i + 1; } runWithMocks( new Runnable() { @Override public void run() { for (int i = 0; i < numTimesToQuery; ++i) { TestHelper.assertExpectedResults( new MergeIterable<>( Ordering.<Result<Object>>natural().nullsFirst(), FunctionalIterable .create(new RangeIterable(expectedResultsRangeStart, expectedResultsRangeEnd)) .transformCat( new Function<Integer, Iterable<Iterable<Result<Object>>>>() { @Override public Iterable<Iterable<Result<Object>>> apply(@Nullable Integer input) { List<Iterable<Result<Object>>> retVal = Lists.newArrayList(); final Map<DruidServer, ServerExpectations> exps = serverExpectationList.get(input); for (ServerExpectations expectations : exps.values()) { for (ServerExpectation expectation : expectations) { retVal.add(expectation.getResults()); } } return retVal; } } ) ), client.run( query.withQuerySegmentSpec( new MultipleIntervalSegmentSpec( Arrays.asList( actualQueryInterval ) ) ) ) ); } } }, mocks.toArray() ); // make sure all the queries were sent down as 'bySegment' for (Capture queryCapture : queryCaptures) { Query capturedQuery = (Query) queryCapture.getValue(); if(expectBySegment) { Assert.assertEquals("true", capturedQuery.getContextValue("bySegment")); } else { Assert.assertTrue( capturedQuery.getContextValue("bySegment") == null || capturedQuery.getContextValue("bySegment").equals("false") ); } } } } private List<Map<DruidServer, ServerExpectations>> populateTimeline( List<Interval> queryIntervals, List<List<Iterable<Result<Object>>>> expectedResults, int numQueryIntervals, List<Object> mocks ) { timeline = new VersionedIntervalTimeline<>(Ordering.natural()); final List<Map<DruidServer, ServerExpectations>> serverExpectationList = Lists.newArrayList(); for (int k = 0; k < numQueryIntervals + 1; ++k) { final int numChunks = expectedResults.get(k).size(); final TreeMap<DruidServer, ServerExpectations> serverExpectations = Maps.newTreeMap(); serverExpectationList.add(serverExpectations); for (int j = 0; j < numChunks; ++j) { DruidServer lastServer = servers[random.nextInt(servers.length)]; if (!serverExpectations.containsKey(lastServer)) { serverExpectations.put(lastServer, new ServerExpectations(lastServer, makeMock(mocks, QueryRunner.class))); } ServerExpectation expectation = new ServerExpectation( String.format("%s_%s", k, j), // interval/chunk queryIntervals.get(numQueryIntervals), makeMock(mocks, DataSegment.class), expectedResults.get(k).get(j) ); serverExpectations.get(lastServer).addExpectation(expectation); ServerSelector selector = new ServerSelector(expectation.getSegment(), new RandomServerSelectorStrategy()); selector.addServer(new QueryableDruidServer(lastServer, null)); final PartitionChunk<ServerSelector> chunk; if (numChunks == 1) { chunk = new SingleElementPartitionChunk<>(selector); } else { String start = null; String end = null; if (j > 0) { start = String.valueOf(j - 1); } if (j + 1 < numChunks) { end = String.valueOf(j); } chunk = new StringPartitionChunk<>(start, end, j, selector); } timeline.add(queryIntervals.get(k), String.valueOf(k), chunk); } } return serverExpectationList; } private Sequence<Result<TimeseriesResultValue>> toQueryableTimeseriesResults( boolean bySegment, Iterable<String> segmentIds, Iterable<Interval> intervals, Iterable<Iterable<Result<TimeseriesResultValue>>> results ) { if(bySegment) { return Sequences.simple( FunctionalIterable .create(segmentIds) .trinaryTransform( intervals, results, new TrinaryFn<String, Interval, Iterable<Result<TimeseriesResultValue>>, Result<TimeseriesResultValue>>() { @Override @SuppressWarnings("unchecked") public Result<TimeseriesResultValue> apply( final String segmentId, final Interval interval, final Iterable<Result<TimeseriesResultValue>> results ) { return new Result( results.iterator().next().getTimestamp(), new BySegmentResultValueClass( Lists.newArrayList(results), segmentId, interval ) ); } } ) ); } else { return Sequences.simple(Iterables.concat(results)); } } private Sequence<Result<TopNResultValue>> toQueryableTopNResults( Iterable<String> segmentIds, Iterable<Interval> intervals, Iterable<Iterable<Result<TopNResultValue>>> results ) { return Sequences.simple( FunctionalIterable .create(segmentIds) .trinaryTransform( intervals, results, new TrinaryFn<String, Interval, Iterable<Result<TopNResultValue>>, Result<TopNResultValue>>() { @Override @SuppressWarnings("unchecked") public Result<TopNResultValue> apply( final String segmentId, final Interval interval, final Iterable<Result<TopNResultValue>> results ) { return new Result( interval.getStart(), new BySegmentResultValueClass( Lists.newArrayList(results), segmentId, interval ) ); } } ) ); } private Sequence<Result<SearchResultValue>> toQueryableSearchResults( Iterable<String> segmentIds, Iterable<Interval> intervals, Iterable<Iterable<Result<SearchResultValue>>> results ) { return Sequences.simple( FunctionalIterable .create(segmentIds) .trinaryTransform( intervals, results, new TrinaryFn<String, Interval, Iterable<Result<SearchResultValue>>, Result<SearchResultValue>>() { @Override @SuppressWarnings("unchecked") public Result<SearchResultValue> apply( final String segmentId, final Interval interval, final Iterable<Result<SearchResultValue>> results ) { return new Result( results.iterator().next().getTimestamp(), new BySegmentResultValueClass( Lists.newArrayList(results), segmentId, interval ) ); } } ) ); } private Sequence<Result<TimeBoundaryResultValue>> toQueryableTimeBoundaryResults( Iterable<String> segmentIds, Iterable<Interval> intervals, Iterable<Iterable<Result<TimeBoundaryResultValue>>> results ) { return Sequences.simple( FunctionalIterable .create(segmentIds) .trinaryTransform( intervals, results, new TrinaryFn<String, Interval, Iterable<Result<TimeBoundaryResultValue>>, Result<TimeBoundaryResultValue>>() { @Override @SuppressWarnings("unchecked") public Result<TimeBoundaryResultValue> apply( final String segmentId, final Interval interval, final Iterable<Result<TimeBoundaryResultValue>> results ) { return new Result( results.iterator().next().getTimestamp(), new BySegmentResultValueClass( Lists.newArrayList(results), segmentId, interval ) ); } } ) ); } private Iterable<Result<TimeseriesResultValue>> makeTimeResults (Object... objects) { if (objects.length % 3 != 0) { throw new ISE("makeTimeResults must be passed arguments in groups of 3, got[%d]", objects.length); } List<Result<TimeseriesResultValue>> retVal = Lists.newArrayListWithCapacity(objects.length / 3); for (int i = 0; i < objects.length; i += 3) { retVal.add( new Result<>( (DateTime) objects[i], new TimeseriesResultValue( ImmutableMap.of( "rows", objects[i + 1], "imps", objects[i + 2], "impers", objects[i + 2], "avg_imps_per_row", ((Number) objects[i + 2]).doubleValue() / ((Number) objects[i + 1]).doubleValue() ) ) ) ); } return retVal; } private Iterable<BySegmentResultValueClass<TimeseriesResultValue>> makeBySegmentTimeResults (Object... objects) { if (objects.length % 5 != 0) { throw new ISE("makeTimeResults must be passed arguments in groups of 5, got[%d]", objects.length); } List<BySegmentResultValueClass<TimeseriesResultValue>> retVal = Lists.newArrayListWithCapacity(objects.length / 5); for (int i = 0; i < objects.length; i += 5) { retVal.add( new BySegmentResultValueClass<TimeseriesResultValue>( Lists.newArrayList( new TimeseriesResultValue( ImmutableMap.of( "rows", objects[i + 1], "imps", objects[i + 2], "impers", objects[i + 2], "avg_imps_per_row", ((Number) objects[i + 2]).doubleValue() / ((Number) objects[i + 1]).doubleValue() ) ) ), (String)objects[i+3], (Interval)objects[i+4] ) ); } return retVal; } private Iterable<Result<TimeseriesResultValue>> makeRenamedTimeResults (Object... objects) { if (objects.length % 3 != 0) { throw new ISE("makeTimeResults must be passed arguments in groups of 3, got[%d]", objects.length); } List<Result<TimeseriesResultValue>> retVal = Lists.newArrayListWithCapacity(objects.length / 3); for (int i = 0; i < objects.length; i += 3) { retVal.add( new Result<>( (DateTime) objects[i], new TimeseriesResultValue( ImmutableMap.of( "rows2", objects[i + 1], "imps", objects[i + 2], "impers2", objects[i + 2] ) ) ) ); } return retVal; } private Iterable<Result<TopNResultValue>> makeTopNResults (Object... objects) { List<Result<TopNResultValue>> retVal = Lists.newArrayList(); int index = 0; while (index < objects.length) { DateTime timestamp = (DateTime) objects[index++]; List<Map<String, Object>> values = Lists.newArrayList(); while (index < objects.length && !(objects[index] instanceof DateTime)) { if (objects.length - index < 3) { throw new ISE( "expect 3 values for each entry in the top list, had %d values left.", objects.length - index ); } final double imps = ((Number) objects[index + 2]).doubleValue(); final double rows = ((Number) objects[index + 1]).doubleValue(); values.add( ImmutableMap.of( TOP_DIM, objects[index], "rows", rows, "imps", imps, "impers", imps, "avg_imps_per_row", imps / rows ) ); index += 3; } retVal.add(new Result<>(timestamp, new TopNResultValue(values))); } return retVal; } private Iterable<Result<TopNResultValue>> makeRenamedTopNResults (Object... objects) { List<Result<TopNResultValue>> retVal = Lists.newArrayList(); int index = 0; while (index < objects.length) { DateTime timestamp = (DateTime) objects[index++]; List<Map<String, Object>> values = Lists.newArrayList(); while (index < objects.length && !(objects[index] instanceof DateTime)) { if (objects.length - index < 3) { throw new ISE( "expect 3 values for each entry in the top list, had %d values left.", objects.length - index ); } final double imps = ((Number) objects[index + 2]).doubleValue(); final double rows = ((Number) objects[index + 1]).doubleValue(); values.add( ImmutableMap.of( TOP_DIM, objects[index], "rows2", rows, "imps", imps, "impers2", imps ) ); index += 3; } retVal.add(new Result<>(timestamp, new TopNResultValue(values))); } return retVal; } private Iterable<Result<SearchResultValue>> makeSearchResults (Object... objects) { List<Result<SearchResultValue>> retVal = Lists.newArrayList(); int index = 0; while (index < objects.length) { DateTime timestamp = (DateTime) objects[index++]; List values = Lists.newArrayList(); while (index < objects.length && !(objects[index] instanceof DateTime)) { values.add(new SearchHit(TOP_DIM, objects[index++].toString())); } retVal.add(new Result<>(timestamp, new SearchResultValue(values))); } return retVal; } private <T> T makeMock(List<Object> mocks, Class<T> clazz) { T obj = EasyMock.createMock(clazz); mocks.add(obj); return obj; } private void runWithMocks(Runnable toRun, Object... mocks) { EasyMock.replay(mocks); toRun.run(); EasyMock.verify(mocks); EasyMock.reset(mocks); } protected CachingClusteredClient makeClient() { return new CachingClusteredClient( new MapQueryToolChestWarehouse( ImmutableMap.<Class<? extends Query>, QueryToolChest>builder() .put( TimeseriesQuery.class, new TimeseriesQueryQueryToolChest(new QueryConfig()) ) .put(TopNQuery.class, new TopNQueryQueryToolChest(new TopNQueryConfig())) .put(SearchQuery.class, new SearchQueryQueryToolChest(new SearchQueryConfig())) .build() ), new TimelineServerView() { @Override public void registerSegmentCallback(Executor exec, SegmentCallback callback) { } @Override public VersionedIntervalTimeline<String, ServerSelector> getTimeline(String dataSource) { return timeline; } @Override public <T> QueryRunner<T> getQueryRunner(DruidServer server) { return serverView.getQueryRunner(server); } @Override public void registerServerCallback(Executor exec, ServerCallback callback) { } }, cache, jsonMapper ); } private static class ServerExpectation<T> { private final String segmentId; private final Interval interval; private final DataSegment segment; private final Iterable<Result<T>> results; public ServerExpectation( String segmentId, Interval interval, DataSegment segment, Iterable<Result<T>> results ) { this.segmentId = segmentId; this.interval = interval; this.segment = segment; this.results = results; } public String getSegmentId() { return segmentId; } public Interval getInterval() { return interval; } public DataSegment getSegment() { return new MyDataSegment(); } public Iterable<Result<T>> getResults() { return results; } private class MyDataSegment extends DataSegment { private MyDataSegment() { super( "", new Interval(0, 1), "", null, null, null, new NoneShardSpec(), null, -1 ); } private final DataSegment baseSegment = segment; @Override @JsonProperty public String getDataSource() { return baseSegment.getDataSource(); } @Override @JsonProperty public Interval getInterval() { return baseSegment.getInterval(); } @Override @JsonProperty public Map<String, Object> getLoadSpec() { return baseSegment.getLoadSpec(); } @Override @JsonProperty public String getVersion() { return baseSegment.getVersion(); } @Override @JsonSerialize @JsonProperty public List<String> getDimensions() { return baseSegment.getDimensions(); } @Override @JsonSerialize @JsonProperty public List<String> getMetrics() { return baseSegment.getMetrics(); } @Override @JsonProperty public ShardSpec getShardSpec() { return baseSegment.getShardSpec(); } @Override @JsonProperty public long getSize() { return baseSegment.getSize(); } @Override public String getIdentifier() { return segmentId; } @Override public SegmentDescriptor toDescriptor() { return baseSegment.toDescriptor(); } @Override public int compareTo(DataSegment dataSegment) { return baseSegment.compareTo(dataSegment); } @Override public boolean equals(Object o) { return baseSegment.equals(o); } @Override public int hashCode() { return baseSegment.hashCode(); } @Override public String toString() { return baseSegment.toString(); } } } private static class ServerExpectations implements Iterable<ServerExpectation> { private final DruidServer server; private final QueryRunner queryRunner; private final List<ServerExpectation> expectations = Lists.newArrayList(); public ServerExpectations( DruidServer server, QueryRunner queryRunner ) { this.server = server; this.queryRunner = queryRunner; } public DruidServer getServer() { return server; } public QueryRunner getQueryRunner() { return queryRunner; } public List<ServerExpectation> getExpectations() { return expectations; } public void addExpectation( ServerExpectation expectation ) { expectations.add(expectation); } @Override public Iterator<ServerExpectation> iterator() { return expectations.iterator(); } } }
server/src/test/java/io/druid/client/CachingClusteredClientTest.java
/* * Druid - a distributed column store. * Copyright (C) 2012, 2013, 2014 Metamarkets Group Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package io.druid.client; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.dataformat.smile.SmileFactory; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; import com.metamx.common.ISE; import com.metamx.common.guava.FunctionalIterable; import com.metamx.common.guava.MergeIterable; import com.metamx.common.guava.Sequence; import com.metamx.common.guava.Sequences; import com.metamx.common.guava.nary.TrinaryFn; import io.druid.query.topn.TopNQuery; import io.druid.query.topn.TopNQueryBuilder; import io.druid.query.topn.TopNQueryConfig; import io.druid.query.topn.TopNQueryQueryToolChest; import io.druid.query.topn.TopNResultValue; import io.druid.client.cache.Cache; import io.druid.client.cache.MapCache; import io.druid.client.selector.QueryableDruidServer; import io.druid.client.selector.RandomServerSelectorStrategy; import io.druid.client.selector.ServerSelector; import io.druid.granularity.PeriodGranularity; import io.druid.granularity.QueryGranularity; import io.druid.jackson.DefaultObjectMapper; import io.druid.query.BySegmentResultValueClass; import io.druid.query.Druids; import io.druid.query.MapQueryToolChestWarehouse; import io.druid.query.Query; import io.druid.query.QueryConfig; import io.druid.query.QueryRunner; import io.druid.query.QueryToolChest; import io.druid.query.Result; import io.druid.query.SegmentDescriptor; import io.druid.query.aggregation.AggregatorFactory; import io.druid.query.aggregation.CountAggregatorFactory; import io.druid.query.aggregation.LongSumAggregatorFactory; import io.druid.query.aggregation.PostAggregator; import io.druid.query.aggregation.post.ArithmeticPostAggregator; import io.druid.query.aggregation.post.FieldAccessPostAggregator; import io.druid.query.filter.DimFilter; import io.druid.query.search.SearchQueryQueryToolChest; import io.druid.query.search.SearchResultValue; import io.druid.query.search.search.InsensitiveContainsSearchQuerySpec; import io.druid.query.search.search.SearchHit; import io.druid.query.search.search.SearchQuery; import io.druid.query.search.search.SearchQueryConfig; import io.druid.query.spec.MultipleIntervalSegmentSpec; import io.druid.query.timeboundary.TimeBoundaryQuery; import io.druid.query.timeboundary.TimeBoundaryResultValue; import io.druid.query.timeseries.TimeseriesQuery; import io.druid.query.timeseries.TimeseriesQueryQueryToolChest; import io.druid.query.timeseries.TimeseriesResultValue; import io.druid.segment.TestHelper; import io.druid.timeline.DataSegment; import io.druid.timeline.VersionedIntervalTimeline; import io.druid.timeline.partition.NoneShardSpec; import io.druid.timeline.partition.PartitionChunk; import io.druid.timeline.partition.ShardSpec; import io.druid.timeline.partition.SingleElementPartitionChunk; import io.druid.timeline.partition.StringPartitionChunk; import org.easymock.Capture; import org.easymock.EasyMock; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Interval; import org.joda.time.Period; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import javax.annotation.Nullable; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.TreeMap; import java.util.concurrent.Executor; /** */ @RunWith(Parameterized.class) public class CachingClusteredClientTest { /** * We want a deterministic test, but we'd also like a bit of randomness for the distribution of segments * across servers. Thus, we loop multiple times and each time use a deterministically created Random instance. * Increase this value to increase exposure to random situations at the expense of test run time. */ private static final int RANDOMNESS = 10; public static final ImmutableMap<String, String> CONTEXT = ImmutableMap.of(); public static final MultipleIntervalSegmentSpec SEG_SPEC = new MultipleIntervalSegmentSpec(ImmutableList.<Interval>of()); public static final String DATA_SOURCE = "test"; private static final List<AggregatorFactory> AGGS = Arrays.asList( new CountAggregatorFactory("rows"), new LongSumAggregatorFactory("imps", "imps"), new LongSumAggregatorFactory("impers", "imps") ); private static final List<PostAggregator> POST_AGGS = Arrays.<PostAggregator>asList( new ArithmeticPostAggregator( "avg_imps_per_row", "/", Arrays.<PostAggregator>asList( new FieldAccessPostAggregator("imps", "imps"), new FieldAccessPostAggregator("rows", "rows") ) ) ); private static final List<AggregatorFactory> RENAMED_AGGS = Arrays.asList( new CountAggregatorFactory("rows2"), new LongSumAggregatorFactory("imps", "imps"), new LongSumAggregatorFactory("impers2", "imps") ); private static final DimFilter DIM_FILTER = null; private static final List<PostAggregator> RENAMED_POST_AGGS = Arrays.asList(); private static final QueryGranularity GRANULARITY = QueryGranularity.DAY; private static final DateTimeZone TIMEZONE = DateTimeZone.forID("America/Los_Angeles"); private static final QueryGranularity PT1H_TZ_GRANULARITY = new PeriodGranularity(new Period("PT1H"), null, TIMEZONE); private static final String TOP_DIM = "a_dim"; @Parameterized.Parameters public static Collection<?> constructorFeeder() throws IOException { return Lists.transform( Lists.newArrayList(new RangeIterable(RANDOMNESS)), new Function<Integer, Object>() { @Override public Object apply(@Nullable Integer input) { return new Object[]{input}; } } ); } protected static final DefaultObjectMapper jsonMapper = new DefaultObjectMapper(new SmileFactory()); static { jsonMapper.getFactory().setCodec(jsonMapper); } private final Random random; protected VersionedIntervalTimeline<String, ServerSelector> timeline; protected TimelineServerView serverView; protected Cache cache; CachingClusteredClient client; DruidServer[] servers; public CachingClusteredClientTest(int randomSeed) { this.random = new Random(randomSeed); } @Before public void setUp() throws Exception { timeline = new VersionedIntervalTimeline<>(Ordering.<String>natural()); serverView = EasyMock.createStrictMock(TimelineServerView.class); cache = MapCache.create(100000); client = makeClient(); servers = new DruidServer[]{ new DruidServer("test1", "test1", 10, "historical", "bye", 0), new DruidServer("test2", "test2", 10, "historical", "bye", 0), new DruidServer("test3", "test3", 10, "historical", "bye", 0), new DruidServer("test4", "test4", 10, "historical", "bye", 0), new DruidServer("test5", "test5", 10, "historical", "bye", 0) }; } @Test @SuppressWarnings("unchecked") public void testTimeseriesCaching() throws Exception { final Druids.TimeseriesQueryBuilder builder = Druids.newTimeseriesQueryBuilder() .dataSource(DATA_SOURCE) .intervals(SEG_SPEC) .filters(DIM_FILTER) .granularity(GRANULARITY) .aggregators(AGGS) .postAggregators(POST_AGGS) .context(CONTEXT); testQueryCaching( builder.build(), new Interval("2011-01-01/2011-01-02"), makeTimeResults(new DateTime("2011-01-01"), 50, 5000), new Interval("2011-01-02/2011-01-03"), makeTimeResults(new DateTime("2011-01-02"), 30, 6000), new Interval("2011-01-04/2011-01-05"), makeTimeResults(new DateTime("2011-01-04"), 23, 85312), new Interval("2011-01-05/2011-01-10"), makeTimeResults( new DateTime("2011-01-05"), 85, 102, new DateTime("2011-01-06"), 412, 521, new DateTime("2011-01-07"), 122, 21894, new DateTime("2011-01-08"), 5, 20, new DateTime("2011-01-09"), 18, 521 ), new Interval("2011-01-05/2011-01-10"), makeTimeResults( new DateTime("2011-01-05T01"), 80, 100, new DateTime("2011-01-06T01"), 420, 520, new DateTime("2011-01-07T01"), 12, 2194, new DateTime("2011-01-08T01"), 59, 201, new DateTime("2011-01-09T01"), 181, 52 ) ); TestHelper.assertExpectedResults( makeRenamedTimeResults( new DateTime("2011-01-01"), 50, 5000, new DateTime("2011-01-02"), 30, 6000, new DateTime("2011-01-04"), 23, 85312, new DateTime("2011-01-05"), 85, 102, new DateTime("2011-01-05T01"), 80, 100, new DateTime("2011-01-06"), 412, 521, new DateTime("2011-01-06T01"), 420, 520, new DateTime("2011-01-07"), 122, 21894, new DateTime("2011-01-07T01"), 12, 2194, new DateTime("2011-01-08"), 5, 20, new DateTime("2011-01-08T01"), 59, 201, new DateTime("2011-01-09"), 18, 521, new DateTime("2011-01-09T01"), 181, 52 ), client.run( builder.intervals("2011-01-01/2011-01-10") .aggregators(RENAMED_AGGS) .postAggregators(RENAMED_POST_AGGS) .build() ) ); } @Test @SuppressWarnings("unchecked") public void testTimeseriesCachingTimeZone() throws Exception { final Druids.TimeseriesQueryBuilder builder = Druids.newTimeseriesQueryBuilder() .dataSource(DATA_SOURCE) .intervals(SEG_SPEC) .filters(DIM_FILTER) .granularity(PT1H_TZ_GRANULARITY) .aggregators(AGGS) .postAggregators(POST_AGGS) .context(CONTEXT); testQueryCaching( builder.build(), new Interval("2011-11-04/2011-11-08"), makeTimeResults( new DateTime("2011-11-04", TIMEZONE), 50, 5000, new DateTime("2011-11-05", TIMEZONE), 30, 6000, new DateTime("2011-11-06", TIMEZONE), 23, 85312, new DateTime("2011-11-07", TIMEZONE), 85, 102 ) ); TestHelper.assertExpectedResults( makeRenamedTimeResults( new DateTime("2011-11-04", TIMEZONE), 50, 5000, new DateTime("2011-11-05", TIMEZONE), 30, 6000, new DateTime("2011-11-06", TIMEZONE), 23, 85312, new DateTime("2011-11-07", TIMEZONE), 85, 102 ), client.run( builder.intervals("2011-11-04/2011-11-08") .aggregators(RENAMED_AGGS) .postAggregators(RENAMED_POST_AGGS) .build() ) ); } @Test @SuppressWarnings("unchecked") public void testTopNCaching() throws Exception { final TopNQueryBuilder builder = new TopNQueryBuilder() .dataSource(DATA_SOURCE) .dimension(TOP_DIM) .metric("imps") .threshold(3) .intervals(SEG_SPEC) .filters(DIM_FILTER) .granularity(GRANULARITY) .aggregators(AGGS) .postAggregators(POST_AGGS) .context(CONTEXT); testQueryCaching( builder.build(), new Interval("2011-01-01/2011-01-02"), makeTopNResults(new DateTime("2011-01-01"), "a", 50, 5000, "b", 50, 4999, "c", 50, 4998), new Interval("2011-01-02/2011-01-03"), makeTopNResults(new DateTime("2011-01-02"), "a", 50, 4997, "b", 50, 4996, "c", 50, 4995), new Interval("2011-01-05/2011-01-10"), makeTopNResults( new DateTime("2011-01-05"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-06"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-08"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-09"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983 ), new Interval("2011-01-05/2011-01-10"), makeTopNResults( new DateTime("2011-01-05T01"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-06T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-08T01"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-09T01"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983 ) ); TestHelper.assertExpectedResults( makeRenamedTopNResults( new DateTime("2011-01-01"), "a", 50, 5000, "b", 50, 4999, "c", 50, 4998, new DateTime("2011-01-02"), "a", 50, 4997, "b", 50, 4996, "c", 50, 4995, new DateTime("2011-01-05"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-05T01"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-06"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-06T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-08"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-08T01"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-09"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983, new DateTime("2011-01-09T01"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983 ), client.run( builder.intervals("2011-01-01/2011-01-10") .metric("imps") .aggregators(RENAMED_AGGS) .postAggregators(RENAMED_POST_AGGS) .build() ) ); } @Test @SuppressWarnings("unchecked") public void testTopNCachingTimeZone() throws Exception { final TopNQueryBuilder builder = new TopNQueryBuilder() .dataSource(DATA_SOURCE) .dimension(TOP_DIM) .metric("imps") .threshold(3) .intervals(SEG_SPEC) .filters(DIM_FILTER) .granularity(PT1H_TZ_GRANULARITY) .aggregators(AGGS) .postAggregators(POST_AGGS) .context(CONTEXT); testQueryCaching( builder.build(), new Interval("2011-11-04/2011-11-08"), makeTopNResults( new DateTime("2011-11-04", TIMEZONE), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-11-05", TIMEZONE), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-11-06", TIMEZONE), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-11-07", TIMEZONE), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986 ) ); TestHelper.assertExpectedResults( makeRenamedTopNResults( new DateTime("2011-11-04", TIMEZONE), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-11-05", TIMEZONE), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-11-06", TIMEZONE), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-11-07", TIMEZONE), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986 ), client.run( builder.intervals("2011-11-04/2011-11-08") .metric("imps") .aggregators(RENAMED_AGGS) .postAggregators(RENAMED_POST_AGGS) .build() ) ); } @Test @SuppressWarnings("unchecked") public void testTopNCachingEmptyResults() throws Exception { final TopNQueryBuilder builder = new TopNQueryBuilder() .dataSource(DATA_SOURCE) .dimension(TOP_DIM) .metric("imps") .threshold(3) .intervals(SEG_SPEC) .filters(DIM_FILTER) .granularity(GRANULARITY) .aggregators(AGGS) .postAggregators(POST_AGGS) .context(CONTEXT); testQueryCaching( builder.build(), new Interval("2011-01-01/2011-01-02"), makeTopNResults(), new Interval("2011-01-02/2011-01-03"), makeTopNResults(), new Interval("2011-01-05/2011-01-10"), makeTopNResults( new DateTime("2011-01-05"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-06"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-08"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-09"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983 ), new Interval("2011-01-05/2011-01-10"), makeTopNResults( new DateTime("2011-01-05T01"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-06T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-08T01"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-09T01"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983 ) ); TestHelper.assertExpectedResults( makeRenamedTopNResults( new DateTime("2011-01-05"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-05T01"), "a", 50, 4994, "b", 50, 4993, "c", 50, 4992, new DateTime("2011-01-06"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-06T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-07T01"), "a", 50, 4991, "b", 50, 4990, "c", 50, 4989, new DateTime("2011-01-08"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-08T01"), "a", 50, 4988, "b", 50, 4987, "c", 50, 4986, new DateTime("2011-01-09"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983, new DateTime("2011-01-09T01"), "a", 50, 4985, "b", 50, 4984, "c", 50, 4983 ), client.run( builder.intervals("2011-01-01/2011-01-10") .metric("imps") .aggregators(RENAMED_AGGS) .postAggregators(RENAMED_POST_AGGS) .build() ) ); } @Test public void testSearchCaching() throws Exception { testQueryCaching( new SearchQuery( DATA_SOURCE, DIM_FILTER, GRANULARITY, 1000, SEG_SPEC, Arrays.asList("a_dim"), new InsensitiveContainsSearchQuerySpec("how"), null, CONTEXT ), new Interval("2011-01-01/2011-01-02"), makeSearchResults(new DateTime("2011-01-01"), "how", "howdy", "howwwwww", "howwy"), new Interval("2011-01-02/2011-01-03"), makeSearchResults(new DateTime("2011-01-02"), "how1", "howdy1", "howwwwww1", "howwy1"), new Interval("2011-01-05/2011-01-10"), makeSearchResults( new DateTime("2011-01-05"), "how2", "howdy2", "howwwwww2", "howww2", new DateTime("2011-01-06"), "how3", "howdy3", "howwwwww3", "howww3", new DateTime("2011-01-07"), "how4", "howdy4", "howwwwww4", "howww4", new DateTime("2011-01-08"), "how5", "howdy5", "howwwwww5", "howww5", new DateTime("2011-01-09"), "how6", "howdy6", "howwwwww6", "howww6" ), new Interval("2011-01-05/2011-01-10"), makeSearchResults( new DateTime("2011-01-05T01"), "how2", "howdy2", "howwwwww2", "howww2", new DateTime("2011-01-06T01"), "how3", "howdy3", "howwwwww3", "howww3", new DateTime("2011-01-07T01"), "how4", "howdy4", "howwwwww4", "howww4", new DateTime("2011-01-08T01"), "how5", "howdy5", "howwwwww5", "howww5", new DateTime("2011-01-09T01"), "how6", "howdy6", "howwwwww6", "howww6" ) ); } @SuppressWarnings("unchecked") public void testQueryCaching( final Query query, Object... args ) { if (args.length % 2 != 0) { throw new ISE("args.length must be divisible by two, was %d", args.length); } final List<Interval> queryIntervals = Lists.newArrayListWithCapacity(args.length / 2); final List<List<Iterable<Result<Object>>>> expectedResults = Lists.newArrayListWithCapacity(queryIntervals.size()); for (int i = 0; i < args.length; i += 2) { final Interval interval = (Interval) args[i]; final Iterable<Result<Object>> results = (Iterable<Result<Object>>) args[i + 1]; if (queryIntervals.size() > 0 && interval.equals(queryIntervals.get(queryIntervals.size() - 1))) { expectedResults.get(expectedResults.size() - 1).add(results); } else { queryIntervals.add(interval); expectedResults.add(Lists.<Iterable<Result<Object>>>newArrayList(results)); } } for (int i = 0; i < queryIntervals.size(); ++i) { timeline = new VersionedIntervalTimeline<>(Ordering.natural()); final int numTimesToQuery = 3; List<Object> mocks = Lists.newArrayList(); mocks.add(serverView); final Interval actualQueryInterval = new Interval( queryIntervals.get(0).getStart(), queryIntervals.get(i).getEnd() ); final List<Map<DruidServer, ServerExpectations>> serverExpectationList = Lists.newArrayList(); for (int k = 0; k < i + 1; ++k) { final int numChunks = expectedResults.get(k).size(); final TreeMap<DruidServer, ServerExpectations> serverExpectations = Maps.newTreeMap(); serverExpectationList.add(serverExpectations); for (int j = 0; j < numChunks; ++j) { DruidServer lastServer = servers[random.nextInt(servers.length)]; if (!serverExpectations.containsKey(lastServer)) { serverExpectations.put(lastServer, new ServerExpectations(lastServer, makeMock(mocks, QueryRunner.class))); } ServerExpectation expectation = new ServerExpectation( String.format("%s_%s", k, j), queryIntervals.get(i), makeMock(mocks, DataSegment.class), expectedResults.get(k).get(j) ); serverExpectations.get(lastServer).addExpectation(expectation); ServerSelector selector = new ServerSelector(expectation.getSegment(), new RandomServerSelectorStrategy()); selector.addServer(new QueryableDruidServer(lastServer, null)); final PartitionChunk<ServerSelector> chunk; if (numChunks == 1) { chunk = new SingleElementPartitionChunk<>(selector); } else { String start = null; String end = null; if (j > 0) { start = String.valueOf(j - 1); } if (j + 1 < numChunks) { end = String.valueOf(j); } chunk = new StringPartitionChunk<>(start, end, j, selector); } timeline.add(queryIntervals.get(k), String.valueOf(k), chunk); } } List<Capture> queryCaptures = Lists.newArrayList(); final Map<DruidServer, ServerExpectations> finalExpectation = serverExpectationList.get( serverExpectationList.size() - 1 ); for (Map.Entry<DruidServer, ServerExpectations> entry : finalExpectation.entrySet()) { DruidServer server = entry.getKey(); ServerExpectations expectations = entry.getValue(); EasyMock.expect(serverView.getQueryRunner(server)).andReturn(expectations.getQueryRunner()).once(); final Capture<? extends Query> capture = new Capture(); queryCaptures.add(capture); QueryRunner queryable = expectations.getQueryRunner(); if (query instanceof TimeseriesQuery) { List<String> segmentIds = Lists.newArrayList(); List<Interval> intervals = Lists.newArrayList(); List<Iterable<Result<TimeseriesResultValue>>> results = Lists.newArrayList(); for (ServerExpectation expectation : expectations) { segmentIds.add(expectation.getSegmentId()); intervals.add(expectation.getInterval()); results.add(expectation.getResults()); } EasyMock.expect(queryable.run(EasyMock.capture(capture))) .andReturn(toQueryableTimeseriesResults(segmentIds, intervals, results)) .once(); } else if (query instanceof TopNQuery) { List<String> segmentIds = Lists.newArrayList(); List<Interval> intervals = Lists.newArrayList(); List<Iterable<Result<TopNResultValue>>> results = Lists.newArrayList(); for (ServerExpectation expectation : expectations) { segmentIds.add(expectation.getSegmentId()); intervals.add(expectation.getInterval()); results.add(expectation.getResults()); } EasyMock.expect(queryable.run(EasyMock.capture(capture))) .andReturn(toQueryableTopNResults(segmentIds, intervals, results)) .once(); } else if (query instanceof SearchQuery) { List<String> segmentIds = Lists.newArrayList(); List<Interval> intervals = Lists.newArrayList(); List<Iterable<Result<SearchResultValue>>> results = Lists.newArrayList(); for (ServerExpectation expectation : expectations) { segmentIds.add(expectation.getSegmentId()); intervals.add(expectation.getInterval()); results.add(expectation.getResults()); } EasyMock.expect(queryable.run(EasyMock.capture(capture))) .andReturn(toQueryableSearchResults(segmentIds, intervals, results)) .once(); } else if (query instanceof TimeBoundaryQuery) { List<String> segmentIds = Lists.newArrayList(); List<Interval> intervals = Lists.newArrayList(); List<Iterable<Result<TimeBoundaryResultValue>>> results = Lists.newArrayList(); for (ServerExpectation expectation : expectations) { segmentIds.add(expectation.getSegmentId()); intervals.add(expectation.getInterval()); results.add(expectation.getResults()); } EasyMock.expect(queryable.run(EasyMock.capture(capture))) .andReturn(toQueryableTimeBoundaryResults(segmentIds, intervals, results)) .once(); } else { throw new ISE("Unknown query type[%s]", query.getClass()); } } final int expectedResultsRangeStart; final int expectedResultsRangeEnd; if (query instanceof TimeBoundaryQuery) { expectedResultsRangeStart = i; expectedResultsRangeEnd = i + 1; } else { expectedResultsRangeStart = 0; expectedResultsRangeEnd = i + 1; } runWithMocks( new Runnable() { @Override public void run() { for (int i = 0; i < numTimesToQuery; ++i) { TestHelper.assertExpectedResults( new MergeIterable<>( Ordering.<Result<Object>>natural().nullsFirst(), FunctionalIterable .create(new RangeIterable(expectedResultsRangeStart, expectedResultsRangeEnd)) .transformCat( new Function<Integer, Iterable<Iterable<Result<Object>>>>() { @Override public Iterable<Iterable<Result<Object>>> apply(@Nullable Integer input) { List<Iterable<Result<Object>>> retVal = Lists.newArrayList(); final Map<DruidServer, ServerExpectations> exps = serverExpectationList.get(input); for (ServerExpectations expectations : exps.values()) { for (ServerExpectation expectation : expectations) { retVal.add(expectation.getResults()); } } return retVal; } } ) ), client.run( query.withQuerySegmentSpec( new MultipleIntervalSegmentSpec( Arrays.asList( actualQueryInterval ) ) ) ) ); } } }, mocks.toArray() ); for (Capture queryCapture : queryCaptures) { Query capturedQuery = (Query) queryCapture.getValue(); Assert.assertEquals("true", capturedQuery.getContextValue("bySegment")); } } } private Sequence<Result<TimeseriesResultValue>> toQueryableTimeseriesResults( Iterable<String> segmentIds, Iterable<Interval> intervals, Iterable<Iterable<Result<TimeseriesResultValue>>> results ) { return Sequences.simple( FunctionalIterable .create(segmentIds) .trinaryTransform( intervals, results, new TrinaryFn<String, Interval, Iterable<Result<TimeseriesResultValue>>, Result<TimeseriesResultValue>>() { @Override @SuppressWarnings("unchecked") public Result<TimeseriesResultValue> apply( final String segmentId, final Interval interval, final Iterable<Result<TimeseriesResultValue>> results ) { return new Result( results.iterator().next().getTimestamp(), new BySegmentResultValueClass( Lists.newArrayList(results), segmentId, interval ) ); } } ) ); } private Sequence<Result<TopNResultValue>> toQueryableTopNResults( Iterable<String> segmentIds, Iterable<Interval> intervals, Iterable<Iterable<Result<TopNResultValue>>> results ) { return Sequences.simple( FunctionalIterable .create(segmentIds) .trinaryTransform( intervals, results, new TrinaryFn<String, Interval, Iterable<Result<TopNResultValue>>, Result<TopNResultValue>>() { @Override @SuppressWarnings("unchecked") public Result<TopNResultValue> apply( final String segmentId, final Interval interval, final Iterable<Result<TopNResultValue>> results ) { return new Result( interval.getStart(), new BySegmentResultValueClass( Lists.newArrayList(results), segmentId, interval ) ); } } ) ); } private Sequence<Result<SearchResultValue>> toQueryableSearchResults( Iterable<String> segmentIds, Iterable<Interval> intervals, Iterable<Iterable<Result<SearchResultValue>>> results ) { return Sequences.simple( FunctionalIterable .create(segmentIds) .trinaryTransform( intervals, results, new TrinaryFn<String, Interval, Iterable<Result<SearchResultValue>>, Result<SearchResultValue>>() { @Override @SuppressWarnings("unchecked") public Result<SearchResultValue> apply( final String segmentId, final Interval interval, final Iterable<Result<SearchResultValue>> results ) { return new Result( results.iterator().next().getTimestamp(), new BySegmentResultValueClass( Lists.newArrayList(results), segmentId, interval ) ); } } ) ); } private Sequence<Result<TimeBoundaryResultValue>> toQueryableTimeBoundaryResults( Iterable<String> segmentIds, Iterable<Interval> intervals, Iterable<Iterable<Result<TimeBoundaryResultValue>>> results ) { return Sequences.simple( FunctionalIterable .create(segmentIds) .trinaryTransform( intervals, results, new TrinaryFn<String, Interval, Iterable<Result<TimeBoundaryResultValue>>, Result<TimeBoundaryResultValue>>() { @Override @SuppressWarnings("unchecked") public Result<TimeBoundaryResultValue> apply( final String segmentId, final Interval interval, final Iterable<Result<TimeBoundaryResultValue>> results ) { return new Result( results.iterator().next().getTimestamp(), new BySegmentResultValueClass( Lists.newArrayList(results), segmentId, interval ) ); } } ) ); } private Iterable<Result<TimeseriesResultValue>> makeTimeResults (Object... objects) { if (objects.length % 3 != 0) { throw new ISE("makeTimeResults must be passed arguments in groups of 3, got[%d]", objects.length); } List<Result<TimeseriesResultValue>> retVal = Lists.newArrayListWithCapacity(objects.length / 3); for (int i = 0; i < objects.length; i += 3) { retVal.add( new Result<>( (DateTime) objects[i], new TimeseriesResultValue( ImmutableMap.of( "rows", objects[i + 1], "imps", objects[i + 2], "impers", objects[i + 2], "avg_imps_per_row", ((Number) objects[i + 2]).doubleValue() / ((Number) objects[i + 1]).doubleValue() ) ) ) ); } return retVal; } private Iterable<Result<TimeseriesResultValue>> makeRenamedTimeResults (Object... objects) { if (objects.length % 3 != 0) { throw new ISE("makeTimeResults must be passed arguments in groups of 3, got[%d]", objects.length); } List<Result<TimeseriesResultValue>> retVal = Lists.newArrayListWithCapacity(objects.length / 3); for (int i = 0; i < objects.length; i += 3) { retVal.add( new Result<>( (DateTime) objects[i], new TimeseriesResultValue( ImmutableMap.of( "rows2", objects[i + 1], "imps", objects[i + 2], "impers2", objects[i + 2] ) ) ) ); } return retVal; } private Iterable<Result<TopNResultValue>> makeTopNResults (Object... objects) { List<Result<TopNResultValue>> retVal = Lists.newArrayList(); int index = 0; while (index < objects.length) { DateTime timestamp = (DateTime) objects[index++]; List<Map<String, Object>> values = Lists.newArrayList(); while (index < objects.length && !(objects[index] instanceof DateTime)) { if (objects.length - index < 3) { throw new ISE( "expect 3 values for each entry in the top list, had %d values left.", objects.length - index ); } final double imps = ((Number) objects[index + 2]).doubleValue(); final double rows = ((Number) objects[index + 1]).doubleValue(); values.add( ImmutableMap.of( TOP_DIM, objects[index], "rows", rows, "imps", imps, "impers", imps, "avg_imps_per_row", imps / rows ) ); index += 3; } retVal.add(new Result<>(timestamp, new TopNResultValue(values))); } return retVal; } private Iterable<Result<TopNResultValue>> makeRenamedTopNResults (Object... objects) { List<Result<TopNResultValue>> retVal = Lists.newArrayList(); int index = 0; while (index < objects.length) { DateTime timestamp = (DateTime) objects[index++]; List<Map<String, Object>> values = Lists.newArrayList(); while (index < objects.length && !(objects[index] instanceof DateTime)) { if (objects.length - index < 3) { throw new ISE( "expect 3 values for each entry in the top list, had %d values left.", objects.length - index ); } final double imps = ((Number) objects[index + 2]).doubleValue(); final double rows = ((Number) objects[index + 1]).doubleValue(); values.add( ImmutableMap.of( TOP_DIM, objects[index], "rows2", rows, "imps", imps, "impers2", imps ) ); index += 3; } retVal.add(new Result<>(timestamp, new TopNResultValue(values))); } return retVal; } private Iterable<Result<SearchResultValue>> makeSearchResults (Object... objects) { List<Result<SearchResultValue>> retVal = Lists.newArrayList(); int index = 0; while (index < objects.length) { DateTime timestamp = (DateTime) objects[index++]; List values = Lists.newArrayList(); while (index < objects.length && !(objects[index] instanceof DateTime)) { values.add(new SearchHit(TOP_DIM, objects[index++].toString())); } retVal.add(new Result<>(timestamp, new SearchResultValue(values))); } return retVal; } private <T> T makeMock(List<Object> mocks, Class<T> clazz) { T obj = EasyMock.createMock(clazz); mocks.add(obj); return obj; } private void runWithMocks(Runnable toRun, Object... mocks) { EasyMock.replay(mocks); toRun.run(); EasyMock.verify(mocks); EasyMock.reset(mocks); } protected CachingClusteredClient makeClient() { return new CachingClusteredClient( new MapQueryToolChestWarehouse( ImmutableMap.<Class<? extends Query>, QueryToolChest>builder() .put( TimeseriesQuery.class, new TimeseriesQueryQueryToolChest(new QueryConfig()) ) .put(TopNQuery.class, new TopNQueryQueryToolChest(new TopNQueryConfig())) .put(SearchQuery.class, new SearchQueryQueryToolChest(new SearchQueryConfig())) .build() ), new TimelineServerView() { @Override public void registerSegmentCallback(Executor exec, SegmentCallback callback) { } @Override public VersionedIntervalTimeline<String, ServerSelector> getTimeline(String dataSource) { return timeline; } @Override public <T> QueryRunner<T> getQueryRunner(DruidServer server) { return serverView.getQueryRunner(server); } @Override public void registerServerCallback(Executor exec, ServerCallback callback) { } }, cache, jsonMapper ); } private static class ServerExpectation<T> { private final String segmentId; private final Interval interval; private final DataSegment segment; private final Iterable<Result<T>> results; public ServerExpectation( String segmentId, Interval interval, DataSegment segment, Iterable<Result<T>> results ) { this.segmentId = segmentId; this.interval = interval; this.segment = segment; this.results = results; } public String getSegmentId() { return segmentId; } public Interval getInterval() { return interval; } public DataSegment getSegment() { return new MyDataSegment(); } public Iterable<Result<T>> getResults() { return results; } private class MyDataSegment extends DataSegment { private MyDataSegment() { super( "", new Interval(0, 1), "", null, null, null, new NoneShardSpec(), null, -1 ); } private final DataSegment baseSegment = segment; @Override @JsonProperty public String getDataSource() { return baseSegment.getDataSource(); } @Override @JsonProperty public Interval getInterval() { return baseSegment.getInterval(); } @Override @JsonProperty public Map<String, Object> getLoadSpec() { return baseSegment.getLoadSpec(); } @Override @JsonProperty public String getVersion() { return baseSegment.getVersion(); } @Override @JsonSerialize @JsonProperty public List<String> getDimensions() { return baseSegment.getDimensions(); } @Override @JsonSerialize @JsonProperty public List<String> getMetrics() { return baseSegment.getMetrics(); } @Override @JsonProperty public ShardSpec getShardSpec() { return baseSegment.getShardSpec(); } @Override @JsonProperty public long getSize() { return baseSegment.getSize(); } @Override public String getIdentifier() { return segmentId; } @Override public SegmentDescriptor toDescriptor() { return baseSegment.toDescriptor(); } @Override public int compareTo(DataSegment dataSegment) { return baseSegment.compareTo(dataSegment); } @Override public boolean equals(Object o) { return baseSegment.equals(o); } @Override public int hashCode() { return baseSegment.hashCode(); } @Override public String toString() { return baseSegment.toString(); } } } private static class ServerExpectations implements Iterable<ServerExpectation> { private final DruidServer server; private final QueryRunner queryRunner; private final List<ServerExpectation> expectations = Lists.newArrayList(); public ServerExpectations( DruidServer server, QueryRunner queryRunner ) { this.server = server; this.queryRunner = queryRunner; } public DruidServer getServer() { return server; } public QueryRunner getQueryRunner() { return queryRunner; } public List<ServerExpectation> getExpectations() { return expectations; } public void addExpectation( ServerExpectation expectation ) { expectations.add(expectation); } @Override public Iterator<ServerExpectation> iterator() { return expectations.iterator(); } } }
add disable populate / use cache tests
server/src/test/java/io/druid/client/CachingClusteredClientTest.java
add disable populate / use cache tests
<ide><path>erver/src/test/java/io/druid/client/CachingClusteredClientTest.java <ide> import com.google.common.base.Function; <ide> import com.google.common.collect.ImmutableList; <ide> import com.google.common.collect.ImmutableMap; <add>import com.google.common.collect.Iterables; <ide> import com.google.common.collect.Lists; <ide> import com.google.common.collect.Maps; <ide> import com.google.common.collect.Ordering; <ide> } <ide> <ide> @Test <add> public void testDisableUseCache() throws Exception <add> { <add> final Druids.TimeseriesQueryBuilder builder = Druids.newTimeseriesQueryBuilder() <add> .dataSource(DATA_SOURCE) <add> .intervals(SEG_SPEC) <add> .filters(DIM_FILTER) <add> .granularity(GRANULARITY) <add> .aggregators(AGGS) <add> .postAggregators(POST_AGGS); <add> <add> testQueryCaching( <add> 1, <add> true, <add> builder.context(ImmutableMap.of("useCache", "false", <add> "populateCache", "true")).build(), <add> new Interval("2011-01-01/2011-01-02"), makeTimeResults(new DateTime("2011-01-01"), 50, 5000) <add> ); <add> <add> Assert.assertEquals(1, cache.getStats().getNumEntries()); <add> Assert.assertEquals(0, cache.getStats().getNumHits()); <add> Assert.assertEquals(0, cache.getStats().getNumMisses()); <add> <add> cache.close("0_0"); <add> <add> testQueryCaching( <add> 1, <add> false, <add> builder.context(ImmutableMap.of("useCache", "false", <add> "populateCache", "false")).build(), <add> new Interval("2011-01-01/2011-01-02"), makeTimeResults(new DateTime("2011-01-01"), 50, 5000) <add> ); <add> <add> Assert.assertEquals(0, cache.getStats().getNumEntries()); <add> Assert.assertEquals(0, cache.getStats().getNumHits()); <add> Assert.assertEquals(0, cache.getStats().getNumMisses()); <add> <add> testQueryCaching( <add> 1, <add> false, <add> builder.context(ImmutableMap.of("useCache", "true", <add> "populateCache", "false")).build(), <add> new Interval("2011-01-01/2011-01-02"), makeTimeResults(new DateTime("2011-01-01"), 50, 5000) <add> ); <add> <add> Assert.assertEquals(0, cache.getStats().getNumEntries()); <add> Assert.assertEquals(0, cache.getStats().getNumHits()); <add> Assert.assertEquals(1, cache.getStats().getNumMisses()); <add> } <add> <add> @Test <ide> @SuppressWarnings("unchecked") <ide> public void testTopNCaching() throws Exception <ide> { <ide> ); <ide> } <ide> <add> public void testQueryCaching(final Query query, Object... args) { <add> testQueryCaching(3, true, query, args); <add> } <add> <ide> @SuppressWarnings("unchecked") <ide> public void testQueryCaching( <del> final Query query, Object... args <add> final int numTimesToQuery, <add> boolean expectBySegment, <add> final Query query, Object... args // does this assume query intervals must be ordered? <ide> ) <ide> { <ide> if (args.length % 2 != 0) { <ide> } <ide> <ide> for (int i = 0; i < queryIntervals.size(); ++i) { <del> timeline = new VersionedIntervalTimeline<>(Ordering.natural()); <del> final int numTimesToQuery = 3; <del> <ide> List<Object> mocks = Lists.newArrayList(); <ide> mocks.add(serverView); <ide> <ide> queryIntervals.get(0).getStart(), queryIntervals.get(i).getEnd() <ide> ); <ide> <del> final List<Map<DruidServer, ServerExpectations>> serverExpectationList = Lists.newArrayList(); <del> <del> for (int k = 0; k < i + 1; ++k) { <del> final int numChunks = expectedResults.get(k).size(); <del> final TreeMap<DruidServer, ServerExpectations> serverExpectations = Maps.newTreeMap(); <del> serverExpectationList.add(serverExpectations); <del> for (int j = 0; j < numChunks; ++j) { <del> DruidServer lastServer = servers[random.nextInt(servers.length)]; <del> if (!serverExpectations.containsKey(lastServer)) { <del> serverExpectations.put(lastServer, new ServerExpectations(lastServer, makeMock(mocks, QueryRunner.class))); <del> } <del> <del> ServerExpectation expectation = new ServerExpectation( <del> String.format("%s_%s", k, j), <del> queryIntervals.get(i), <del> makeMock(mocks, DataSegment.class), <del> expectedResults.get(k).get(j) <del> ); <del> serverExpectations.get(lastServer).addExpectation(expectation); <del> <del> ServerSelector selector = new ServerSelector(expectation.getSegment(), new RandomServerSelectorStrategy()); <del> selector.addServer(new QueryableDruidServer(lastServer, null)); <del> <del> final PartitionChunk<ServerSelector> chunk; <del> if (numChunks == 1) { <del> chunk = new SingleElementPartitionChunk<>(selector); <del> } else { <del> String start = null; <del> String end = null; <del> if (j > 0) { <del> start = String.valueOf(j - 1); <del> } <del> if (j + 1 < numChunks) { <del> end = String.valueOf(j); <del> } <del> chunk = new StringPartitionChunk<>(start, end, j, selector); <del> } <del> timeline.add(queryIntervals.get(k), String.valueOf(k), chunk); <del> } <del> } <add> final List<Map<DruidServer, ServerExpectations>> serverExpectationList = populateTimeline( <add> queryIntervals, <add> expectedResults, <add> i, <add> mocks <add> ); <ide> <ide> List<Capture> queryCaptures = Lists.newArrayList(); <ide> final Map<DruidServer, ServerExpectations> finalExpectation = serverExpectationList.get( <ide> DruidServer server = entry.getKey(); <ide> ServerExpectations expectations = entry.getValue(); <ide> <del> EasyMock.expect(serverView.getQueryRunner(server)).andReturn(expectations.getQueryRunner()).once(); <add> <add> EasyMock.expect(serverView.getQueryRunner(server)) <add> .andReturn(expectations.getQueryRunner()) <add> .once(); <ide> <ide> final Capture<? extends Query> capture = new Capture(); <ide> queryCaptures.add(capture); <ide> intervals.add(expectation.getInterval()); <ide> results.add(expectation.getResults()); <ide> } <add> <ide> EasyMock.expect(queryable.run(EasyMock.capture(capture))) <del> .andReturn(toQueryableTimeseriesResults(segmentIds, intervals, results)) <add> .andReturn(toQueryableTimeseriesResults(expectBySegment, segmentIds, intervals, results)) <ide> .once(); <add> <ide> } else if (query instanceof TopNQuery) { <ide> List<String> segmentIds = Lists.newArrayList(); <ide> List<Interval> intervals = Lists.newArrayList(); <ide> mocks.toArray() <ide> ); <ide> <add> // make sure all the queries were sent down as 'bySegment' <ide> for (Capture queryCapture : queryCaptures) { <ide> Query capturedQuery = (Query) queryCapture.getValue(); <del> Assert.assertEquals("true", capturedQuery.getContextValue("bySegment")); <del> } <del> } <add> if(expectBySegment) { <add> Assert.assertEquals("true", capturedQuery.getContextValue("bySegment")); <add> } <add> else { <add> Assert.assertTrue( <add> capturedQuery.getContextValue("bySegment") == null || <add> capturedQuery.getContextValue("bySegment").equals("false") <add> ); <add> } <add> } <add> } <add> } <add> <add> private List<Map<DruidServer, ServerExpectations>> populateTimeline( <add> List<Interval> queryIntervals, <add> List<List<Iterable<Result<Object>>>> expectedResults, <add> int numQueryIntervals, <add> List<Object> mocks <add> ) <add> { <add> timeline = new VersionedIntervalTimeline<>(Ordering.natural()); <add> <add> final List<Map<DruidServer, ServerExpectations>> serverExpectationList = Lists.newArrayList(); <add> <add> for (int k = 0; k < numQueryIntervals + 1; ++k) { <add> final int numChunks = expectedResults.get(k).size(); <add> final TreeMap<DruidServer, ServerExpectations> serverExpectations = Maps.newTreeMap(); <add> serverExpectationList.add(serverExpectations); <add> for (int j = 0; j < numChunks; ++j) { <add> DruidServer lastServer = servers[random.nextInt(servers.length)]; <add> if (!serverExpectations.containsKey(lastServer)) { <add> serverExpectations.put(lastServer, new ServerExpectations(lastServer, makeMock(mocks, QueryRunner.class))); <add> } <add> <add> ServerExpectation expectation = new ServerExpectation( <add> String.format("%s_%s", k, j), // interval/chunk <add> queryIntervals.get(numQueryIntervals), <add> makeMock(mocks, DataSegment.class), <add> expectedResults.get(k).get(j) <add> ); <add> serverExpectations.get(lastServer).addExpectation(expectation); <add> <add> ServerSelector selector = new ServerSelector(expectation.getSegment(), new RandomServerSelectorStrategy()); <add> selector.addServer(new QueryableDruidServer(lastServer, null)); <add> <add> final PartitionChunk<ServerSelector> chunk; <add> if (numChunks == 1) { <add> chunk = new SingleElementPartitionChunk<>(selector); <add> } else { <add> String start = null; <add> String end = null; <add> if (j > 0) { <add> start = String.valueOf(j - 1); <add> } <add> if (j + 1 < numChunks) { <add> end = String.valueOf(j); <add> } <add> chunk = new StringPartitionChunk<>(start, end, j, selector); <add> } <add> timeline.add(queryIntervals.get(k), String.valueOf(k), chunk); <add> } <add> } return serverExpectationList; <ide> } <ide> <ide> private Sequence<Result<TimeseriesResultValue>> toQueryableTimeseriesResults( <add> boolean bySegment, <ide> Iterable<String> segmentIds, <ide> Iterable<Interval> intervals, <ide> Iterable<Iterable<Result<TimeseriesResultValue>>> results <ide> ) <ide> { <add> if(bySegment) { <ide> return Sequences.simple( <ide> FunctionalIterable <ide> .create(segmentIds) <ide> } <ide> ) <ide> ); <add> } else { <add> return Sequences.simple(Iterables.concat(results)); <add> } <ide> } <ide> <ide> private Sequence<Result<TopNResultValue>> toQueryableTopNResults( <ide> return retVal; <ide> } <ide> <add> private Iterable<BySegmentResultValueClass<TimeseriesResultValue>> makeBySegmentTimeResults <add> (Object... objects) <add> { <add> if (objects.length % 5 != 0) { <add> throw new ISE("makeTimeResults must be passed arguments in groups of 5, got[%d]", objects.length); <add> } <add> <add> List<BySegmentResultValueClass<TimeseriesResultValue>> retVal = Lists.newArrayListWithCapacity(objects.length / 5); <add> for (int i = 0; i < objects.length; i += 5) { <add> retVal.add( <add> new BySegmentResultValueClass<TimeseriesResultValue>( <add> Lists.newArrayList( <add> new TimeseriesResultValue( <add> ImmutableMap.of( <add> "rows", objects[i + 1], <add> "imps", objects[i + 2], <add> "impers", objects[i + 2], <add> "avg_imps_per_row", <add> ((Number) objects[i + 2]).doubleValue() / ((Number) objects[i + 1]).doubleValue() <add> ) <add> ) <add> ), <add> (String)objects[i+3], <add> (Interval)objects[i+4] <add> <add> ) <add> ); <add> } <add> return retVal; <add> } <add> <ide> private Iterable<Result<TimeseriesResultValue>> makeRenamedTimeResults <ide> (Object... objects) <ide> {
JavaScript
mit
1432b07431b5520690273a3a116ce283cde65844
0
clupascu/regex-crossword-goodies,wolfascu/regex-crossword-goodies
(function (w, d) { 'use strict'; var config, logger; config = w.goodies = w.goodies || { }; config.debugMode = !!localStorage.goodiesDebugMode; logger = {}; ['debug', 'log', 'info', 'error', 'warn'].forEach(function (funcName) { logger[funcName] = function () { if (config.debugMode) { console[funcName].apply(console, arguments); } }; }); function addPlayerPuzzlesPageFunctionality(scope, titleElement) { var chk, ui = d.createElement('div'); ui.innerHTML = '<input type="checkbox" id="chkTodo" /> &nbsp;' + '<label for="chkTodo">Only show unsolved unambiguous puzzles</label>'; titleElement.parentElement.insertBefore(ui, titleElement.nextElementSibling); chk = d.getElementById('chkTodo'); chk.addEventListener('click', function () { scope.allPuzzles = scope.allPuzzles || scope.puzzles; if (this.checked) { scope.puzzles = scope.allPuzzles.filter(function (p) { return !(p.solved || p.ambiguous); }); } else { scope.puzzles = scope.allPuzzles; } scope.$apply(); }); } function addPuzzleFunctionality(scope, topElement) { var puzzleAdapter, ui, persistence, puzzle = scope.puzzle, Cell = function (inputElement, angularModel) { var self = this; this.ui = inputElement; this.regexes = []; inputElement.addEventListener('input', function () { self.regexes.forEach(function (re) { re.validate(); }); }); this.registerRegexElement = function (regexElement) { this.regexes.push(regexElement); }; this.getValue = function () { if (inputElement.classList.contains('space')) { return ' '; } if (inputElement.value) { return inputElement.value.toUpperCase(); } return null; }; this.setValue = function (newValue) { if (newValue === ' ') { inputElement.classList.add('space'); } else { inputElement.classList.remove('space'); } angularModel.value = newValue; }; }, RegexElement = function (cells, expression, uiClueElement) { var self = this; cells.forEach(function (c) { c.registerRegexElement(self); }); this.regex = new RegExp('^(?:' + expression + ')$'); this.validate = function () { logger.debug('Validating: ' + this.regex); var answer = '', i, chr; for (i = 0; i < cells.length; i++) { chr = cells[i].getValue(); if (chr) { answer += chr; } else { answer = null; break; } } uiClueElement.classList.remove('clue-error'); uiClueElement.classList.remove('clue-ok'); if (answer) { if (answer.match(this.regex)) { uiClueElement.classList.add('clue-ok'); } else { uiClueElement.classList.add('clue-error'); } } }; }, RectangularPuzzleAdapter = function () { var rowCount, colCount, self = this, emptyCellPlaceholder = '\xB7'; this.regexElements = []; function getCells(textBoxes) { var cells = [], i, j; for (i = 0; i < rowCount; i++) { for (j = 0; j < colCount; j++) { cells.push(new Cell( textBoxes[i * colCount + j], scope.puzzle.answer.rows[i][j] )); } } return cells; } function addHorizontalRegexElements(cells) { var usedCells = [], patterns, i, clueUIElements = topElement.querySelectorAll('th.clue'); for (i = 0; i < rowCount; i++) { usedCells = cells.slice(i * colCount, (i + 1) * colCount); patterns = scope.puzzle.patternsY.patterns[i]; // left clue if (patterns.a.value) { self.regexElements.push( new RegexElement(usedCells, patterns.a.value, clueUIElements[i * 2]) ); } // right clue if (patterns.b.value) { self.regexElements.push( new RegexElement(usedCells, patterns.b.value, clueUIElements[i * 2 + 1]) ); } } } function addVerticalRegexElements(cells) { var usedCells, patterns, i, j, clueUIElements = topElement.querySelectorAll('div.clue'); for (j = 0; j < colCount; j++) { usedCells = []; for (i = 0; i < rowCount; i++) { usedCells.push(cells[i * colCount + j]); } patterns = scope.puzzle.patternsX.patterns[j]; // top clue if (patterns.a.value) { self.regexElements.push( new RegexElement(usedCells, patterns.a.value, clueUIElements[j]) ); } // bottom clue if (patterns.b.value) { self.regexElements.push( new RegexElement(usedCells, patterns.b.value, clueUIElements[j + colCount]) ); } } } this.init = function () { var textBoxes; rowCount = scope.puzzle.answer.rows.length; colCount = scope.puzzle.answer.rows[0].length; logger.debug('Rectangular puzzle ' + colCount + ' by ' + rowCount); textBoxes = topElement.querySelectorAll('input.char'); if (textBoxes.length < rowCount * colCount) { logger.debug('Waiting for textboxes to render...'); w.setTimeout(function () { self.init(); }, 10); return; } this.cells = getCells(textBoxes); addHorizontalRegexElements(this.cells); addVerticalRegexElements(this.cells); }; this.getAnswer = function () { var answer = ''; this.cells.forEach(function (c) { answer += c.getValue() || emptyCellPlaceholder; }); return answer; }; this.setAnswer = function (answer) { var i; for (i = 0; i < this.cells.length; i++) { if (i >= answer.length) { break; } this.cells[i].setValue(answer[i]); scope.$apply(); } logger.warn('todo: set answer to: ' + answer); }; }, HexagonalPuzzleAdapter = function () { this.init = function () { logger.warn('todo!'); }; }, UI = function () { var addButton = function (name) { var newBtn, controlContainer; newBtn = d.createElement('button'); newBtn.type = 'button'; newBtn.classList.add('btn'); newBtn.classList.add('btn-default'); newBtn.textContent = name; controlContainer = topElement.querySelector('h1'); controlContainer.appendChild(document.createTextNode(' ')); controlContainer.appendChild(newBtn); return newBtn; }; this.init = function () { var saveBtn, loadBtn; saveBtn = addButton('Save'); saveBtn.addEventListener('click', this.onSaveClick); loadBtn = addButton('Load'); loadBtn.addEventListener('click', this.onLoadClick); }; this.getTextBoxes = function () { return topElement.querySelectorAll('input.char'); }; }; if (!puzzle) { // puzzle not yet loaded... return; } persistence = { load: function () { return w.prompt('Enter previous solution:'); }, save: function (currentSolution) { w.prompt('Put this in a safe place:', currentSolution); } }; ui = new UI(); puzzleAdapter = puzzle.hexagonal ? new HexagonalPuzzleAdapter() : new RectangularPuzzleAdapter(); ui.onLoadClick = function () { logger.info('loading.'); puzzleAdapter.setAnswer(persistence.load()); }; ui.onSaveClick = function () { logger.info('saving.'); persistence.save(puzzleAdapter.getAnswer()); }; ui.init(); puzzleAdapter.init(); puzzleAdapter.onAnswerChange = function () { puzzleAdapter.validate(); }; } function onViewChanged() { logger.log('View changed!'); var scope, puzzleListTitleElement, puzzleElement = d.querySelector('div.challenge-puzzle') || d.querySelector('div.playerpuzzle'); if (puzzleElement) { scope = angular.element(puzzleElement).scope(); addPuzzleFunctionality(scope, puzzleElement); return; } puzzleListTitleElement = d.querySelector('div.container h2'); if (puzzleListTitleElement && puzzleListTitleElement.textContent === 'Puzzles') { scope = angular.element(puzzleListTitleElement).scope(); addPlayerPuzzlesPageFunctionality(scope, puzzleListTitleElement); } } function appendStyles() { var styleTag = d.createElement('style'); styleTag.type = 'text/css'; styleTag.textContent = '.clue-error{color:#a94442;}.clue-ok{color:#3c763d;}'; d.head.appendChild(styleTag); } function start() { config.rootElement = d.querySelector('div[ng-view]'); if (!config.rootElement) { logger.warn('root element not yet found.'); w.setTimeout(start, 100); return; } appendStyles(); logger.info('root element found!'); config.rootScope = angular.element(config.rootElement).scope().$root; config.rootScope.$on('$viewContentLoaded', onViewChanged); onViewChanged(); } start(); }(window, document));
src/regex_crossword.js
(function (w, d) { 'use strict'; var config, logger; config = w.goodies = w.goodies || { }; config.debugMode = !!localStorage.goodiesDebugMode; logger = {}; ['debug', 'log', 'info', 'error', 'warn'].forEach(function (funcName) { logger[funcName] = function () { if (config.debugMode) { console[funcName].apply(console, arguments); } }; }); function addPlayerPuzzlesPageFunctionality(scope, titleElement) { var chk, ui = d.createElement('div'); ui.innerHTML = '<input type="checkbox" id="chkTodo" /> &nbsp;' + '<label for="chkTodo">Only show unsolved unambiguous puzzles</label>'; titleElement.parentElement.insertBefore(ui, titleElement.nextElementSibling); chk = d.getElementById('chkTodo'); chk.addEventListener('click', function () { scope.allPuzzles = scope.allPuzzles || scope.puzzles; if (this.checked) { scope.puzzles = scope.allPuzzles.filter(function (p) { return !(p.solved || p.ambiguous); }); } else { scope.puzzles = scope.allPuzzles; } scope.$apply(); }); } function addPuzzleFunctionality(scope, topElement) { var puzzleAdapter, ui, persistence, puzzle = scope.puzzle, Cell = function (inputElement, angularModel) { var self = this; this.ui = inputElement; this.regexes = []; inputElement.addEventListener('input', function () { self.regexes.forEach(function (re) { re.validate(); }); }); this.registerRegexElement = function (regexElement) { this.regexes.push(regexElement); }; this.getValue = function () { if (inputElement.classList.contains('space')) { return ' '; } if (inputElement.value) { return inputElement.value.toUpperCase(); } return null; }; this.setValue = function (newValue) { if (newValue === ' ') { inputElement.classList.add('space'); } else { inputElement.classList.remove('space'); } angularModel.value = newValue; }; }, RegexElement = function (cells, expression, uiClueElement) { var self = this; cells.forEach(function (c) { c.registerRegexElement(self); }); this.regex = new RegExp('^(?:' + expression + ')$'); this.validate = function () { logger.debug('Validating: ' + this.regex); var answer = '', i, chr; for (i = 0; i < cells.length; i++) { chr = cells[i].getValue(); if (chr) { answer += chr; } else { answer = null; break; } } uiClueElement.classList.remove('clue-error'); uiClueElement.classList.remove('clue-ok'); if (answer) { if (answer.match(this.regex)) { uiClueElement.classList.add('clue-ok'); } else { uiClueElement.classList.add('clue-error'); } } }; }, RectangularPuzzleAdapter = function () { var rowCount, colCount, self = this; this.regexElements = []; function getCells(textBoxes) { var cells = [], i, j; for (i = 0; i < rowCount; i++) { for (j = 0; j < colCount; j++) { cells.push(new Cell( textBoxes[i * colCount + j], scope.puzzle.answer.rows[i][j] )); } } return cells; } function addHorizontalRegexElements(cells) { var usedCells = [], patterns, i, clueUIElements = topElement.querySelectorAll('th.clue'); for (i = 0; i < rowCount; i++) { usedCells = cells.slice(i * colCount, (i + 1) * colCount); patterns = scope.puzzle.patternsY.patterns[i]; // left clue if (patterns.a.value) { self.regexElements.push( new RegexElement(usedCells, patterns.a.value, clueUIElements[i * 2]) ); } // right clue if (patterns.b.value) { self.regexElements.push( new RegexElement(usedCells, patterns.b.value, clueUIElements[i * 2 + 1]) ); } } } function addVerticalRegexElements(cells) { var usedCells, patterns, i, j, clueUIElements = topElement.querySelectorAll('div.clue'); for (j = 0; j < colCount; j++) { usedCells = []; for (i = 0; i < rowCount; i++) { usedCells.push(cells[i * colCount + j]); } patterns = scope.puzzle.patternsX.patterns[j]; // top clue if (patterns.a.value) { self.regexElements.push( new RegexElement(usedCells, patterns.a.value, clueUIElements[j]) ); } // bottom clue if (patterns.b.value) { self.regexElements.push( new RegexElement(usedCells, patterns.b.value, clueUIElements[j + colCount]) ); } } } this.init = function () { var textBoxes, cells; rowCount = scope.puzzle.answer.rows.length; colCount = scope.puzzle.answer.rows[0].length; logger.debug('Rectangular puzzle ' + colCount + ' by ' + rowCount); textBoxes = topElement.querySelectorAll('input.char'); if (textBoxes.length < rowCount * colCount) { logger.debug('Waiting for textboxes to render...'); w.setTimeout(function () { self.init(); }, 10); return; } cells = getCells(textBoxes); addHorizontalRegexElements(cells); addVerticalRegexElements(cells); }; this.getAnswer = function () { return 'todo!'; }; this.setAnswer = function (answer) { logger.warn('todo: set answer to: ' + answer); }; }, HexagonalPuzzleAdapter = function () { this.init = function () { logger.warn('todo!'); }; }, UI = function () { var addButton = function (name) { var newBtn, controlContainer; newBtn = d.createElement('button'); newBtn.type = 'button'; newBtn.classList.add('btn'); newBtn.classList.add('btn-default'); newBtn.textContent = name; controlContainer = topElement.querySelector('h1'); controlContainer.appendChild(document.createTextNode(' ')); controlContainer.appendChild(newBtn); return newBtn; }; this.init = function () { var saveBtn, loadBtn; saveBtn = addButton('Save'); saveBtn.addEventListener('click', function () { logger.log('save'); }); loadBtn = addButton('Load'); loadBtn.addEventListener('click', this.onLoadClick); }; this.getTextBoxes = function () { return topElement.querySelectorAll('input.char'); }; }; if (!puzzle) { // puzzle not yet loaded... return; } persistence = { load: function () { return w.prompt('Enter previous solution:'); }, save: function (currentSolution) { w.prompt('Put this in a safe place:', currentSolution); } }; ui = new UI(); puzzleAdapter = puzzle.hexagonal ? new HexagonalPuzzleAdapter() : new RectangularPuzzleAdapter(); ui.onLoadClick = function () { logger.info('loading.'); puzzleAdapter.setAnswer(persistence.load()); }; ui.onSaveClick = function () { logger.info('saving.'); persistence.save(puzzleAdapter.getAnswer()); }; ui.init(); puzzleAdapter.init(); puzzleAdapter.onAnswerChange = function () { puzzleAdapter.validate(); }; } function onViewChanged() { logger.log('View changed!'); var scope, puzzleListTitleElement, puzzleElement = d.querySelector('div.challenge-puzzle') || d.querySelector('div.playerpuzzle'); if (puzzleElement) { scope = angular.element(puzzleElement).scope(); addPuzzleFunctionality(scope, puzzleElement); return; } puzzleListTitleElement = d.querySelector('div.container h2'); if (puzzleListTitleElement && puzzleListTitleElement.textContent === 'Puzzles') { scope = angular.element(puzzleListTitleElement).scope(); addPlayerPuzzlesPageFunctionality(scope, puzzleListTitleElement); } } function appendStyles() { var styleTag = d.createElement('style'); styleTag.type = 'text/css'; styleTag.textContent = '.clue-error{color:#a94442;}.clue-ok{color:#3c763d;}'; d.head.appendChild(styleTag); } function start() { config.rootElement = d.querySelector('div[ng-view]'); if (!config.rootElement) { logger.warn('root element not yet found.'); w.setTimeout(start, 100); return; } appendStyles(); logger.info('root element found!'); config.rootScope = angular.element(config.rootElement).scope().$root; config.rootScope.$on('$viewContentLoaded', onViewChanged); onViewChanged(); } start(); }(window, document));
made persistence work
src/regex_crossword.js
made persistence work
<ide><path>rc/regex_crossword.js <ide> }, <ide> <ide> RectangularPuzzleAdapter = function () { <del> var rowCount, colCount, self = this; <add> var rowCount, colCount, <add> self = this, <add> emptyCellPlaceholder = '\xB7'; <ide> <ide> this.regexElements = []; <ide> <ide> } <ide> <ide> this.init = function () { <del> var textBoxes, cells; <add> var textBoxes; <ide> <ide> rowCount = scope.puzzle.answer.rows.length; <ide> colCount = scope.puzzle.answer.rows[0].length; <ide> return; <ide> } <ide> <del> cells = getCells(textBoxes); <del> <del> addHorizontalRegexElements(cells); <del> addVerticalRegexElements(cells); <add> this.cells = getCells(textBoxes); <add> <add> addHorizontalRegexElements(this.cells); <add> addVerticalRegexElements(this.cells); <ide> }; <ide> <ide> this.getAnswer = function () { <del> return 'todo!'; <add> var answer = ''; <add> <add> this.cells.forEach(function (c) { <add> answer += c.getValue() || emptyCellPlaceholder; <add> }); <add> <add> return answer; <ide> }; <ide> <ide> this.setAnswer = function (answer) { <add> var i; <add> <add> for (i = 0; i < this.cells.length; i++) { <add> if (i >= answer.length) { <add> break; <add> } <add> <add> this.cells[i].setValue(answer[i]); <add> <add> scope.$apply(); <add> } <add> <ide> logger.warn('todo: set answer to: ' + answer); <ide> }; <ide> }, <ide> var saveBtn, loadBtn; <ide> <ide> saveBtn = addButton('Save'); <del> saveBtn.addEventListener('click', function () { <del> logger.log('save'); <del> }); <add> saveBtn.addEventListener('click', this.onSaveClick); <ide> <ide> loadBtn = addButton('Load'); <ide> loadBtn.addEventListener('click', this.onLoadClick);
Java
apache-2.0
f2ded74fba14098368855019eae2d629ea94b1db
0
saurfang/elephant-bird,twitter/elephant-bird,skinzer/elephant-bird,rubanm/elephant-bird,rubanm/elephant-bird,twitter/elephant-bird,laurentgo/elephant-bird,EugenCepoi/elephant-bird,RainyWang103/elephant-bird,xizhououyang/elephant-bird,EugenCepoi/elephant-bird,rangadi/elephant-bird
package com.twitter.elephantbird.mapreduce.output; import java.io.IOException; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import com.twitter.elephantbird.mapreduce.input.BinaryConverterProvider; import com.twitter.elephantbird.mapreduce.io.BinaryBlockWriter; import com.twitter.elephantbird.mapreduce.io.BinaryConverter; import com.twitter.elephantbird.mapreduce.io.GenericWritable; import com.twitter.elephantbird.util.HadoopCompat; import com.twitter.elephantbird.util.HadoopUtils; import org.apache.hadoop.conf.Configuration; /** * Generic OutputFormat for records to be stored as lzo-compressed protobuf blocks. */ public class LzoGenericBlockOutputFormat<M> extends LzoOutputFormat<M, GenericWritable<M>> { private static String CLASS_CONF_KEY = "elephantbird.class.for.LzoGenericBlockOutputFormat"; private static String GENERIC_ENCODER_KEY = "elephantbird.encoder.class.for.LzoGenericBlockOutputFormat"; public static void setGenericConverterClassConf(Class<?> clazz, Configuration conf) { HadoopUtils.setClassConf(conf, GENERIC_ENCODER_KEY, clazz); } public static void setClassConf(Class<?> clazz, Configuration conf) { HadoopUtils.setClassConf(conf, CLASS_CONF_KEY, clazz); } @Override public RecordWriter<M, GenericWritable<M>> getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException { Configuration conf = HadoopCompat.getConfiguration(job); String encoderClassName = conf.get(GENERIC_ENCODER_KEY); Class<?> typeRef = null; Class<?> encoderClazz = null; BinaryConverterProvider<?> converterProvider = null; try { String typeRefClass = conf.get(CLASS_CONF_KEY); typeRef = conf.getClassByName(typeRefClass); encoderClazz = conf.getClassByName(encoderClassName); converterProvider = (BinaryConverterProvider<?>)encoderClazz.newInstance(); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException("failed to instantiate class '" + encoderClassName + "'", e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } BinaryConverter<?> converter = converterProvider.getConverter(conf); return new LzoBinaryBlockRecordWriter<M, GenericWritable<M>>(new BinaryBlockWriter( getOutputStream(job), typeRef, converter)); } }
core/src/main/java/com/twitter/elephantbird/mapreduce/output/LzoGenericBlockOutputFormat.java
package com.twitter.elephantbird.mapreduce.output; import java.io.IOException; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import com.twitter.elephantbird.mapreduce.input.BinaryConverterProvider; import com.twitter.elephantbird.mapreduce.io.BinaryBlockWriter; import com.twitter.elephantbird.mapreduce.io.BinaryConverter; import com.twitter.elephantbird.mapreduce.io.GenericWritable; import com.twitter.elephantbird.util.HadoopCompat; import com.twitter.elephantbird.util.HadoopUtils; import org.apache.hadoop.conf.Configuration; /** * Generic OutputFormat for records to be stored as lzo-compressed protobuf blocks. */ public class LzoGenericBlockOutputFormat<M> extends LzoOutputFormat<M, GenericWritable<M>> { private static String CLASS_CONF_KEY = "elephantbird.class.for.LzoGenericBlockOutputFormat"; private static String GENERIC_ENCODER_KEY = "elephantbird.encoder.class.for.LzoGenericBlockOutputFormat"; public static void setGenericConverterClassConf(Class<?> clazz, Configuration conf) { HadoopUtils.setClassConf(conf, GENERIC_ENCODER_KEY, clazz); } public static void setClassConf(Class<?> clazz, Configuration conf) { HadoopUtils.setClassConf(conf, CLASS_CONF_KEY, clazz); } @Override public RecordWriter<M, GenericWritable<M>> getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException { Configuration conf = HadoopCompat.getConfiguration(job); String encoderClassName = conf.get(GENERIC_ENCODER_KEY); Class<?> typeRef = null; Class<?> encoderClazz = null; BinaryConverterProvider<?> converterProvider = null; try { String typeRefClass = conf.get(CLASS_CONF_KEY); typeRef = conf.getClassByName(typeRefClass); encoderClazz = conf.getClassByName(encoderClassName); converterProvider = (BinaryConverterProvider<?>)encoderClazz.newInstance(); } catch (Exception e) { throw new RuntimeException("failed to instantiate class '" + encoderClassName + "'", e); } BinaryConverter<?> converter = converterProvider.getConverter(conf); return new LzoBinaryBlockRecordWriter<M, GenericWritable<M>>(new BinaryBlockWriter( getOutputStream(job), typeRef, converter)); } }
catch specific exceptions
core/src/main/java/com/twitter/elephantbird/mapreduce/output/LzoGenericBlockOutputFormat.java
catch specific exceptions
<ide><path>ore/src/main/java/com/twitter/elephantbird/mapreduce/output/LzoGenericBlockOutputFormat.java <ide> typeRef = conf.getClassByName(typeRefClass); <ide> encoderClazz = conf.getClassByName(encoderClassName); <ide> converterProvider = (BinaryConverterProvider<?>)encoderClazz.newInstance(); <del> } catch (Exception e) { <add> } catch (ClassNotFoundException e) { <add> throw new RuntimeException(e); <add> } catch (InstantiationException e) { <ide> throw new RuntimeException("failed to instantiate class '" + encoderClassName + "'", e); <add> } catch (IllegalAccessException e) { <add> throw new RuntimeException(e); <ide> } <ide> <ide> BinaryConverter<?> converter = converterProvider.getConverter(conf);
JavaScript
bsd-2-clause
e65ab29ce032214ec1bd4bbb376ea54c24d6300f
0
openpeer/rolodex,openpeer/rolodex,cadorn/rolodex,cadorn/rolodex
const ASSERT = require("assert"); const PASSPORT_GITHUB = require("passport-github"); const GITHUB = require("github"); const WAITFOR = require("waitfor"); exports.init = function(rolodex, passport, config, options, callback) { try { ASSERT.equal(typeof config.passport.clientID, "string"); ASSERT.equal(typeof config.passport.clientSecret, "string"); passport.use(new PASSPORT_GITHUB.Strategy({ clientID: config.passport.clientID, clientSecret: config.passport.clientSecret, callbackURL: config.callbackURL }, function(accessToken, refreshToken, profile, done) { return done(null, { "github": { "id": profile.id, "email": profile.emails[0].value, "username": profile.username, "accessToken": accessToken } }); })); function getAPI(passportSession) { ASSERT.equal(typeof passportSession, "object"); var github = new GITHUB({ version: "3.0.0", timeout: 5 * 1000 }); github.authenticate({ type: "oauth", token: passportSession.accessToken }); return github; } return callback(null, { fetchContacts: function(passportSession, service, options, done) { if (service.fetching) return done(null); if (service.contactsTotal > 0 && options.refetch !== true) return done(null); function callback(err) { service.fetching = false; return done.apply(null, arguments); } var github = getAPI(passportSession); service.fetching = true; function ensureUserInfo(callback) { if (service.username !== null && options.refetch !== true) { return callback(null); } console.log("[rolodex][github] Fetch user info for: " + passportSession.username); return github.user.get({}, function(err, user) { if (err) return callback(err); /* { "login": "cadorn", "id": 18679, "avatar_url": "https://secure.gravatar.com/avatar/3a5539ba54c87e6571d5801c5dd43ccc?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png", "gravatar_id": "3a5539ba54c87e6571d5801c5dd43ccc", "url": "https://api.github.com/users/cadorn", "html_url": "https://github.com/cadorn", "followers_url": "https://api.github.com/users/cadorn/followers", "following_url": "https://api.github.com/users/cadorn/following", "gists_url": "https://api.github.com/users/cadorn/gists{/gist_id}", "starred_url": "https://api.github.com/users/cadorn/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/cadorn/subscriptions", "organizations_url": "https://api.github.com/users/cadorn/orgs", "repos_url": "https://api.github.com/users/cadorn/repos", "events_url": "https://api.github.com/users/cadorn/events{/privacy}", "received_events_url": "https://api.github.com/users/cadorn/received_events", "type": "User", "name": "Christoph Dorn", "company": "", "blog": "http://ChristophDorn.com", "location": "Canada", "email": "[email protected]", "hireable": true, "bio": "", "public_repos": 76, "followers": 69, "following": 13, "created_at": "2008-07-28T14:16:20Z", "updated_at": "2013-04-26T16:57:57Z", "public_gists": 18, "meta": { "x-ratelimit-limit": "5000", "x-ratelimit-remaining": "4992" } } */ // TODO: Add this as a full contact. var firstLoad = (service.username === null) ? true : false; service.username = user.login; service.contactsTotal = user.following; if (firstLoad) { return service.load(callback); } else { return callback(null); } }); } return ensureUserInfo(function(err) { if (err) return callback(err); if (service.contactsFetched === service.contactsTotal && options.refetch !== true) return callback(null); console.log("[rolodex][github] Fetch contacts for: " + service.username); var existingContacts = {}; for (var contactId in service.contacts) { existingContacts[contactId] = true; } function processResult(res, callback) { res.forEach(function(user) { /* { "login": "LawrenceGunn", "id": 689166, "avatar_url": "https://secure.gravatar.com/avatar/c812a2a87bfa2f251a23b9bcda130607?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png", "gravatar_id": "c812a2a87bfa2f251a23b9bcda130607", "url": "https://api.github.com/users/LawrenceGunn", "html_url": "https://github.com/LawrenceGunn", "followers_url": "https://api.github.com/users/LawrenceGunn/followers", "following_url": "https://api.github.com/users/LawrenceGunn/following", "gists_url": "https://api.github.com/users/LawrenceGunn/gists{/gist_id}", "starred_url": "https://api.github.com/users/LawrenceGunn/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/LawrenceGunn/subscriptions", "organizations_url": "https://api.github.com/users/LawrenceGunn/orgs", "repos_url": "https://api.github.com/users/LawrenceGunn/repos", "events_url": "https://api.github.com/users/LawrenceGunn/events{/privacy}", "received_events_url": "https://api.github.com/users/LawrenceGunn/received_events", "type": "User" } */ service.contacts[user.login] = { "gravatar_id": user.gravatar_id }; delete existingContacts[user.login]; }); service.contactsFetched = Object.keys(service.contacts).length; if (!github.hasNextPage(res)) { return callback(null); } return github.getNextPage(res, function(err, res) { if (err) return callback(err); return processResult(res, callback); }); } return github.user.getFollowing({ per_page: "100" }, function(err, res) { if (err) return callback(err); return processResult(res, function(err) { if (err) return callback(err); for (var contactId in existingContacts) { delete service.contacts[contactId]; } service.contactsFetched = Object.keys(service.contacts).length; if (service.contactsFetched !== service.contactsTotal) { console.warn("[rolodex][github] ERROR: `contactsFetched` (" + service.contactsFetched + ") != `contactsTotal` (" + service.contactsTotal + ")"); } return service.save(function(err) { if (err) return callback(err); // All done. return callback(null); }); }); }); }); } }); /* var fetchFields = { "alias": "login", "name": "name", "email": "email" }; // Don't fetch again if all fields have already been fetched. if (service._contacts[contact]) { var allFieldsFound = true; for (var targetName in fetchFields) { if (typeof service._contacts[contact][targetName] === "undefined") { allFieldsFound = false; } } if (allFieldsFound) return } waitfor(function(done) { return github.user.getFrom({ user: contact }, function(err, user) { if (err) return done(err); { "login": "zaach", "id": 3903, "avatar_url": "https://secure.gravatar.com/avatar/a7657b2354d983b2c8db0d6226d1ce20?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png", "gravatar_id": "a7657b2354d983b2c8db0d6226d1ce20", "url": "https://api.github.com/users/zaach", "html_url": "https://github.com/zaach", "followers_url": "https://api.github.com/users/zaach/followers", "following_url": "https://api.github.com/users/zaach/following", "gists_url": "https://api.github.com/users/zaach/gists{/gist_id}", "starred_url": "https://api.github.com/users/zaach/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/zaach/subscriptions", "organizations_url": "https://api.github.com/users/zaach/orgs", "repos_url": "https://api.github.com/users/zaach/repos", "events_url": "https://api.github.com/users/zaach/events{/privacy}", "received_events_url": "https://api.github.com/users/zaach/received_events", "type": "User", "name": "Zach Carter", "company": "Mozilla", "blog": "twitter.com/zii", "location": "San Francisco, CA", "email": "[email protected]", "hireable": false, "bio": null, "public_repos": 52, "followers": 177, "following": 42, "created_at": "2008-03-26T15:01:36Z", "updated_at": "2013-04-25T14:29:58Z", "public_gists": 59 } if (!service._contacts[contact]) { service._contacts[contact] = {}; } for (var targetName in fetchFields) { service._contacts[contact][targetName] = user[fetchFields[targetName]]; } service.stats.fetchedContacts = Object.keys(service._contacts).length; return done(null); }); }); */ } catch(err) { return callback(err); } }
lib/services/github/plugin.js
const ASSERT = require("assert"); const PASSPORT_GITHUB = require("passport-github"); const GITHUB = require("github"); const WAITFOR = require("waitfor"); exports.init = function(rolodex, passport, config, options, callback) { try { ASSERT.equal(typeof config.passport.clientID, "string"); ASSERT.equal(typeof config.passport.clientSecret, "string"); passport.use(new PASSPORT_GITHUB.Strategy({ clientID: config.passport.clientID, clientSecret: config.passport.clientSecret, callbackURL: config.callbackURL }, function(accessToken, refreshToken, profile, done) { return done(null, { "github": { "id": profile.id, "email": profile.emails[0].value, "username": profile.username, "accessToken": accessToken } }); })); function getAPI(passportSession) { ASSERT.equal(typeof passportSession, "object"); var github = new GITHUB({ version: "3.0.0", timeout: 5 * 1000 }); github.authenticate({ type: "oauth", token: passportSession.accessToken }); return github; } return callback(null, { fetchContacts: function(passportSession, service, options, done) { if (service.fetching) return done(null); if (service.contactsTotal > 0 && options.refetch !== true) return done(null); function callback(err) { service.fetching = false; return done.apply(null, arguments); } var github = getAPI(passportSession); service.fetching = true; function ensureUserInfo(callback) { if (service.username !== null && options.refetch !== true) { return callback(null); } console.log("[rolodex][github] Fetch user info for: " + passportSession.username); return github.user.get({}, function(err, user) { if (err) return callback(err); /* { "login": "cadorn", "id": 18679, "avatar_url": "https://secure.gravatar.com/avatar/3a5539ba54c87e6571d5801c5dd43ccc?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png", "gravatar_id": "3a5539ba54c87e6571d5801c5dd43ccc", "url": "https://api.github.com/users/cadorn", "html_url": "https://github.com/cadorn", "followers_url": "https://api.github.com/users/cadorn/followers", "following_url": "https://api.github.com/users/cadorn/following", "gists_url": "https://api.github.com/users/cadorn/gists{/gist_id}", "starred_url": "https://api.github.com/users/cadorn/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/cadorn/subscriptions", "organizations_url": "https://api.github.com/users/cadorn/orgs", "repos_url": "https://api.github.com/users/cadorn/repos", "events_url": "https://api.github.com/users/cadorn/events{/privacy}", "received_events_url": "https://api.github.com/users/cadorn/received_events", "type": "User", "name": "Christoph Dorn", "company": "", "blog": "http://ChristophDorn.com", "location": "Canada", "email": "[email protected]", "hireable": true, "bio": "", "public_repos": 76, "followers": 69, "following": 13, "created_at": "2008-07-28T14:16:20Z", "updated_at": "2013-04-26T16:57:57Z", "public_gists": 18, "meta": { "x-ratelimit-limit": "5000", "x-ratelimit-remaining": "4992" } } */ // TODO: Add this as a full contact. var firstLoad = (service.username === null) ? true : false; service.username = user.login; service.contactsTotal = user.following; if (firstLoad) { return service.load(callback); } else { return callback(null); } }); } return ensureUserInfo(function(err) { if (err) return callback(err); if (service.contactsFetched === service.contactsTotal && options.refetch !== true) return callback(null); console.log("[rolodex][github] Fetch contacts for: " + service.username); var existingContacts = {}; for (var contactId in service.contacts) { existingContacts[contactId] = true; } function processResult(res, callback) { res.forEach(function(user) { /* { "login": "LawrenceGunn", "id": 689166, "avatar_url": "https://secure.gravatar.com/avatar/c812a2a87bfa2f251a23b9bcda130607?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png", "gravatar_id": "c812a2a87bfa2f251a23b9bcda130607", "url": "https://api.github.com/users/LawrenceGunn", "html_url": "https://github.com/LawrenceGunn", "followers_url": "https://api.github.com/users/LawrenceGunn/followers", "following_url": "https://api.github.com/users/LawrenceGunn/following", "gists_url": "https://api.github.com/users/LawrenceGunn/gists{/gist_id}", "starred_url": "https://api.github.com/users/LawrenceGunn/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/LawrenceGunn/subscriptions", "organizations_url": "https://api.github.com/users/LawrenceGunn/orgs", "repos_url": "https://api.github.com/users/LawrenceGunn/repos", "events_url": "https://api.github.com/users/LawrenceGunn/events{/privacy}", "received_events_url": "https://api.github.com/users/LawrenceGunn/received_events", "type": "User" } */ service.contacts[user.login] = { "gravatar_id": user.gravatar_id }; delete existingContacts[user.login]; }); service.contactsFetched = Object.keys(service.contacts).length; if (!github.hasNextPage(res)) { return callback(null); } return github.getNextPage(res, function(err, res) { if (err) return callback(err); return processResult(res, callback); }); } return github.user.getFollowing({ per_page: "10" }, function(err, res) { if (err) return callback(err); return processResult(res, function(err) { if (err) return callback(err); for (var contactId in existingContacts) { delete service.contacts[contactId]; } service.contactsFetched = Object.keys(service.contacts).length; if (service.contactsFetched !== service.contactsTotal) { console.warn("[rolodex][github] ERROR: `contactsFetched` (" + service.contactsFetched + ") != `contactsTotal` (" + service.contactsTotal + ")"); } return service.save(function(err) { if (err) return callback(err); // All done. return callback(null); }); }); }); }); } }); /* var fetchFields = { "alias": "login", "name": "name", "email": "email" }; // Don't fetch again if all fields have already been fetched. if (service._contacts[contact]) { var allFieldsFound = true; for (var targetName in fetchFields) { if (typeof service._contacts[contact][targetName] === "undefined") { allFieldsFound = false; } } if (allFieldsFound) return } waitfor(function(done) { return github.user.getFrom({ user: contact }, function(err, user) { if (err) return done(err); { "login": "zaach", "id": 3903, "avatar_url": "https://secure.gravatar.com/avatar/a7657b2354d983b2c8db0d6226d1ce20?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png", "gravatar_id": "a7657b2354d983b2c8db0d6226d1ce20", "url": "https://api.github.com/users/zaach", "html_url": "https://github.com/zaach", "followers_url": "https://api.github.com/users/zaach/followers", "following_url": "https://api.github.com/users/zaach/following", "gists_url": "https://api.github.com/users/zaach/gists{/gist_id}", "starred_url": "https://api.github.com/users/zaach/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/zaach/subscriptions", "organizations_url": "https://api.github.com/users/zaach/orgs", "repos_url": "https://api.github.com/users/zaach/repos", "events_url": "https://api.github.com/users/zaach/events{/privacy}", "received_events_url": "https://api.github.com/users/zaach/received_events", "type": "User", "name": "Zach Carter", "company": "Mozilla", "blog": "twitter.com/zii", "location": "San Francisco, CA", "email": "[email protected]", "hireable": false, "bio": null, "public_repos": 52, "followers": 177, "following": 42, "created_at": "2008-03-26T15:01:36Z", "updated_at": "2013-04-25T14:29:58Z", "public_gists": 59 } if (!service._contacts[contact]) { service._contacts[contact] = {}; } for (var targetName in fetchFields) { service._contacts[contact][targetName] = user[fetchFields[targetName]]; } service.stats.fetchedContacts = Object.keys(service._contacts).length; return done(null); }); }); */ } catch(err) { return callback(err); } }
100 per page (github api)
lib/services/github/plugin.js
100 per page (github api)
<ide><path>ib/services/github/plugin.js <ide> }); <ide> } <ide> return github.user.getFollowing({ <del> per_page: "10" <add> per_page: "100" <ide> }, function(err, res) { <ide> if (err) return callback(err); <ide> return processResult(res, function(err) {
Java
epl-1.0
22da37e341cec878bfe0a85947d8f0c84fdea328
0
css-iter/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,css-iter/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,css-iter/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,css-iter/org.csstudio.iter,css-iter/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,css-iter/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,css-iter/org.csstudio.iter,css-iter/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter
/******************************************************************************* * Copyright (c) 2010-2014 ITER Organization. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.iter.pydev.configurator; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.ui.preferences.ScopedPreferenceStore; import org.python.pydev.core.IInterpreterInfo; import org.python.pydev.debug.core.PydevDebugPlugin; import org.python.pydev.debug.newconsole.PydevConsoleConstants; import org.python.pydev.plugin.PydevPlugin; import org.python.pydev.ui.interpreters.JythonInterpreterManager; import org.python.pydev.ui.interpreters.PythonInterpreterManager; import org.python.pydev.ui.pythonpathconf.InterpreterInfo; public class InterpreterUtils { private static final String[] PLUGIN_TO_ADD_IN_PYTHON_PATH = new String[] { "org.eclipse.ui", "org.eclipse.ui.workbench", "org.eclipse.swt", "org.eclipse.jface", "org.csstudio.swt.xygraph", "org.csstudio.swt.widgets", "org.csstudio.opibuilder", "org.csstudio.opibuilder.widgets" }; /** * Creates a Python interpreter by attempting to read where the python * command being used originates. * * @param name * @param monitor * @throws Exception */ public static boolean createPythonInterpreter(String name, IProgressMonitor monitor) throws Exception { final String interpreterExePath = PythonUtils.getProbablePythonPath(); if (interpreterExePath == null) { return false; } File scanPluginDir = BundleUtils.getBundleLocation("org.csstudio.scan"); final File scanJythonLibDir = new File(scanPluginDir, "jython"); String scanJythonLibPath = null; if (scanJythonLibDir.exists()) { scanJythonLibPath = scanJythonLibDir.getAbsolutePath(); } final PythonInterpreterManager man = (PythonInterpreterManager) PydevPlugin .getPythonInterpreterManager(); InterpreterInfo info = null; try { info = man.getInterpreterInfo(name, monitor); } catch (Exception ne) { info = null; } if (info != null && interpreterExePath.equals(info.getExecutableOrJar()) && (scanJythonLibPath == null || info.libs .contains(scanJythonLibPath))) { // All paths are correct - Nothing to do return false; } // Create new interpreter // Horrible Hack warning: This code is copied from parts of Pydev to set // up the interpreter and save it. info = (InterpreterInfo) man.createInterpreterInfo(interpreterExePath, monitor, false); if (info == null) { return false; } info.setName(name); final Set<String> names = new HashSet<String>(1); names.add(name); // Add Scan Jython Lib dir if (scanJythonLibPath != null) { info.libs.add(scanJythonLibPath); } man.setInfos(new IInterpreterInfo[] { info }, names, monitor); PydevPlugin.getWorkspace().save(true, monitor); Activator.getLogger().info( "PyDev workspace saved with interpreter: " + name); man.clearCaches(); return true; } /** * We programmatically create a Jython Interpreter so that the user does not * have to. * * @throws Exception */ public static boolean createJythonInterpreter(final String name, final IProgressMonitor mon) throws Exception { final JythonInterpreterManager man = (JythonInterpreterManager) PydevPlugin .getJythonInterpreterManager(); InterpreterInfo info = null; try { info = man.getInterpreterInfo(name, mon); } catch (Exception ne) { info = null; } // Code copies from Pydev when the user chooses a Jython interpreter // - these are the defaults. final File jydir = BundleUtils.getBundleLocation("org.python.jython"); final File exeFile = new File(jydir, "jython.jar"); if (info != null && exeFile.getAbsolutePath().equals(info.getExecutableOrJar())) { // All paths are correct - Nothing to do return false; } // Create new interpreter // Horrible Hack warning: This code is copied from parts of Pydev to set // up the interpreter and save it. final File script = PydevPlugin .getScriptWithinPySrc("interpreterInfo.py"); if (!script.exists()) { throw new Exception("The file specified does not exist: " + script); } info = (InterpreterInfo) man.createInterpreterInfo( exeFile.getAbsolutePath(), mon, false); if (info == null) { return false; } // Add PyDev Libs dir File pydevdir = BundleUtils.getBundleLocation("org.python.pydev"); final File pydevLibDir = new File(pydevdir, "libs"); if (pydevLibDir.exists()) { info.libs.add(pydevLibDir.getCanonicalPath()); } // Add Scan Jython Lib dir File scanPluginDir = BundleUtils.getBundleLocation("org.csstudio.scan"); final File scanJythonLibDir = new File(scanPluginDir, "jython"); if (scanJythonLibDir.exists()) { info.libs.add(scanJythonLibDir.getCanonicalPath()); } for (String pluginToAdd : PLUGIN_TO_ADD_IN_PYTHON_PATH) { File bundleLocation = BundleUtils.getBundleLocation(pluginToAdd); if (bundleLocation != null && bundleLocation.exists()) { info.libs.add(bundleLocation.getCanonicalPath()); } } // java, java.lang, etc should be found now info.restoreCompiledLibs(mon); info.setName(name); final Set<String> names = new HashSet<String>(1); names.add(name); man.setInfos(new IInterpreterInfo[] { info }, names, mon); PydevPlugin.getWorkspace().save(true, mon); Activator.getLogger().info( "PyDev workspace saved with interpreter: " + name); man.clearCaches(); updateInitialInterpreterCmds(); return true; } private static void updateInitialInterpreterCmds() throws IOException { File scanPluginDir = BundleUtils.getBundleLocation("org.csstudio.scan"); final File scanJythonLibDir = new File(scanPluginDir, "jython"); if (scanJythonLibDir.exists()) { final ScopedPreferenceStore prefStore = new ScopedPreferenceStore( InstanceScope.INSTANCE, PydevDebugPlugin.getPluginID()); prefStore.setValue( PydevConsoleConstants.INITIAL_INTERPRETER_CMDS, PydevConsoleConstants.DEFAULT_INITIAL_INTERPRETER_CMDS + "sys.path.append('" + scanJythonLibDir.getAbsolutePath() + "')\n" + "from scan_client import *\n"); } } }
products/ITER/plugins/org.csstudio.iter.pydev.configurator/src/org/csstudio/iter/pydev/configurator/InterpreterUtils.java
/******************************************************************************* * Copyright (c) 2010-2014 ITER Organization. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.iter.pydev.configurator; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.ui.preferences.ScopedPreferenceStore; import org.python.pydev.core.IInterpreterInfo; import org.python.pydev.debug.core.PydevDebugPlugin; import org.python.pydev.debug.newconsole.PydevConsoleConstants; import org.python.pydev.plugin.PydevPlugin; import org.python.pydev.ui.interpreters.JythonInterpreterManager; import org.python.pydev.ui.interpreters.PythonInterpreterManager; import org.python.pydev.ui.pythonpathconf.InterpreterInfo; public class InterpreterUtils { private static final String[] PLUGIN_TO_ADD_IN_PYTHON_PATH = new String[] { "org.eclipse.ui", "org.eclipse.ui.workbench", "org.eclipse.swt", "org.eclipse.jface", "org.csstudio.swt.xygraph", "org.csstudio.swt.widgets", "org.csstudio.opibuilder", "org.csstudio.opibuilder.widgets" }; /** * Creates a Python interpreter by attempting to read where the python * command being used originates. * * @param name * @param monitor * @throws Exception */ public static boolean createPythonInterpreter(String name, IProgressMonitor monitor) throws Exception { final String interpreterExePath = PythonUtils.getProbablePythonPath(); if (interpreterExePath == null) { return false; } File scanPluginDir = BundleUtils.getBundleLocation("org.csstudio.scan"); final File scanJythonLibDir = new File(scanPluginDir, "jython"); String scanJythonLibPath = null; if (scanJythonLibDir.exists()) { scanJythonLibPath = scanJythonLibDir.getAbsolutePath(); } final PythonInterpreterManager man = (PythonInterpreterManager) PydevPlugin .getPythonInterpreterManager(); InterpreterInfo info = null; try { info = man.getInterpreterInfo(name, monitor); } catch (Exception ne) { info = null; } if (info != null && interpreterExePath.equals(info.getExecutableOrJar()) && (scanJythonLibPath == null || info.libs .contains(scanJythonLibPath))) { // All paths are correct - Nothing to do return false; } // Create new interpreter // Horrible Hack warning: This code is copied from parts of Pydev to set // up the interpreter and save it. info = (InterpreterInfo) man.createInterpreterInfo(interpreterExePath, monitor, false); if (info == null) { return false; } info.setName(name); final Set<String> names = new HashSet<String>(1); names.add(name); // Add Scan Jython Lib dir if (scanJythonLibPath != null) { info.libs.add(scanJythonLibPath); } man.setInfos(new IInterpreterInfo[] { info }, names, monitor); PydevPlugin.getWorkspace().save(true, monitor); Activator.getLogger().info( "PyDev workspace saved with interpreter: " + name); man.clearCaches(); return true; } /** * We programmatically create a Jython Interpreter so that the user does not * have to. * * @throws Exception */ public static boolean createJythonInterpreter(final String name, final IProgressMonitor mon) throws Exception { final JythonInterpreterManager man = (JythonInterpreterManager) PydevPlugin .getJythonInterpreterManager(); InterpreterInfo info = null; try { info = man.getInterpreterInfo(name, mon); } catch (Exception ne) { info = null; } // Code copies from Pydev when the user chooses a Jython interpreter // - these are the defaults. final File jydir = BundleUtils.getBundleLocation("org.python.jython"); final File exeFile = new File(jydir, "jython.jar"); if (info != null && exeFile.getAbsolutePath().equals(info.getExecutableOrJar())) { // All paths are correct - Nothing to do return false; } // Create new interpreter // Horrible Hack warning: This code is copied from parts of Pydev to set // up the interpreter and save it. final File script = PydevPlugin .getScriptWithinPySrc("interpreterInfo.py"); if (!script.exists()) { throw new Exception("The file specified does not exist: " + script); } info = (InterpreterInfo) man.createInterpreterInfo( exeFile.getAbsolutePath(), mon, false); if (info == null) { return false; } // Add PyDev Libs dir File pydevdir = BundleUtils.getBundleLocation("org.python.pydev"); final File pydevLibDir = new File(pydevdir, "libs"); if (pydevLibDir.exists()) { info.libs.add(pydevLibDir.getCanonicalPath()); } // Add PyDev Jython Lib dir File pydevjythondir = BundleUtils .getBundleLocation("org.python.pydev.jython"); final File pydevjythonLibDir = new File(pydevjythondir, "Lib"); if (pydevjythonLibDir.exists()) { info.libs.add(pydevjythonLibDir.getCanonicalPath()); } // Add Scan Jython Lib dir File scanPluginDir = BundleUtils.getBundleLocation("org.csstudio.scan"); final File scanJythonLibDir = new File(scanPluginDir, "jython"); if (scanJythonLibDir.exists()) { info.libs.add(scanJythonLibDir.getCanonicalPath()); } for (String pluginToAdd : PLUGIN_TO_ADD_IN_PYTHON_PATH) { File bundleLocation = BundleUtils.getBundleLocation(pluginToAdd); if (bundleLocation != null && bundleLocation.exists()) { info.libs.add(bundleLocation.getCanonicalPath()); } } // java, java.lang, etc should be found now info.restoreCompiledLibs(mon); info.setName(name); final Set<String> names = new HashSet<String>(1); names.add(name); man.setInfos(new IInterpreterInfo[] { info }, names, mon); PydevPlugin.getWorkspace().save(true, mon); Activator.getLogger().info( "PyDev workspace saved with interpreter: " + name); man.clearCaches(); updateInitialInterpreterCmds(); return true; } private static void updateInitialInterpreterCmds() throws IOException { File scanPluginDir = BundleUtils.getBundleLocation("org.csstudio.scan"); final File scanJythonLibDir = new File(scanPluginDir, "jython"); if (scanJythonLibDir.exists()) { final ScopedPreferenceStore prefStore = new ScopedPreferenceStore( InstanceScope.INSTANCE, PydevDebugPlugin.getPluginID()); prefStore.setValue( PydevConsoleConstants.INITIAL_INTERPRETER_CMDS, PydevConsoleConstants.DEFAULT_INITIAL_INTERPRETER_CMDS + "sys.path.append('" + scanJythonLibDir.getAbsolutePath() + "')\n" + "from scan_client import *\n"); } } }
ITER: Fixed Jython interpreter config
products/ITER/plugins/org.csstudio.iter.pydev.configurator/src/org/csstudio/iter/pydev/configurator/InterpreterUtils.java
ITER: Fixed Jython interpreter config
<ide><path>roducts/ITER/plugins/org.csstudio.iter.pydev.configurator/src/org/csstudio/iter/pydev/configurator/InterpreterUtils.java <ide> info.libs.add(pydevLibDir.getCanonicalPath()); <ide> } <ide> <del> // Add PyDev Jython Lib dir <del> File pydevjythondir = BundleUtils <del> .getBundleLocation("org.python.pydev.jython"); <del> final File pydevjythonLibDir = new File(pydevjythondir, "Lib"); <del> if (pydevjythonLibDir.exists()) { <del> info.libs.add(pydevjythonLibDir.getCanonicalPath()); <del> } <del> <ide> // Add Scan Jython Lib dir <ide> File scanPluginDir = BundleUtils.getBundleLocation("org.csstudio.scan"); <ide> final File scanJythonLibDir = new File(scanPluginDir, "jython");
Java
apache-2.0
69163ccc912103329ce3c24c1a55c8aafa2e76e5
0
lightbody/browsermob-proxy,kyroskoh/browsermob-proxy,jekh/browsermob-proxy,88rabbit/browsermob-proxy,netproteus/browsermob-proxy,lightbody/browsermob-proxy,fhernandez173/browsermob-proxy,bltb/browsermob-proxy,88rabbit/browsermob-proxy,iandeveseleer/browsermob-proxy,webmetrics/browsermob-proxy,kyroskoh/browsermob-proxy,iandeveseleer/browsermob-proxy,tommywo/browsermob-proxy,Jimmy-Gao/browsermob-proxy,jekh/browsermob-proxy,fhernandez173/browsermob-proxy,browserup/browserup-proxy,browserup/browserup-proxy,bltb/browsermob-proxy,bltb/browsermob-proxy,tommywo/browsermob-proxy,fhernandez173/browsermob-proxy,browserup/browserup-proxy,iandeveseleer/browsermob-proxy,kyroskoh/browsermob-proxy,lightbody/browsermob-proxy,netproteus/browsermob-proxy,netproteus/browsermob-proxy,browserup/browserup-proxy,stevenliuit/browsermob-proxy,jekh/browsermob-proxy,88rabbit/browsermob-proxy,tommywo/browsermob-proxy
package org.browsermob.proxy.http; import cz.mallat.uasparser.CachingOnlineUpdateUASparser; import cz.mallat.uasparser.UASparser; import cz.mallat.uasparser.UserAgentInfo; import org.apache.http.*; import org.apache.http.HttpConnection; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.auth.*; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.*; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.protocol.ClientContext; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.ClientConnectionRequest; import org.apache.http.conn.ConnectionPoolTimeoutException; import org.apache.http.conn.ManagedClientConnection; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.cookie.Cookie; import org.apache.http.cookie.params.CookieSpecPNames; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestExecutor; import org.browsermob.core.har.*; import org.browsermob.proxy.util.*; import org.java_bandwidthlimiter.StreamManager; import org.eclipse.jetty.util.MultiMap; import org.eclipse.jetty.util.UrlEncoded; import org.xbill.DNS.Cache; import org.xbill.DNS.DClass; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class BrowserMobHttpClient { private static final int BUFFER = 4096; private static final Log LOG = new Log(); private Har har; private String harPageRef; private boolean captureHeaders; private boolean captureContent; private SimulatedSocketFactory socketFactory; private TrustingSSLSocketFactory sslSocketFactory; private ThreadSafeClientConnManager httpClientConnMgr; private DefaultHttpClient httpClient; private List<BlacklistEntry> blacklistEntries = null; private WhitelistEntry whitelistEntry = null; private List<RewriteRule> rewriteRules = new CopyOnWriteArrayList<RewriteRule>(); private List<RequestInterceptor> requestInterceptors = new CopyOnWriteArrayList<RequestInterceptor>(); private List<ResponseInterceptor> responseInterceptors = new CopyOnWriteArrayList<ResponseInterceptor>(); private HashMap<String, String> additionalHeaders = new LinkedHashMap<String, String>(); private int requestTimeout; private AtomicBoolean allowNewRequests = new AtomicBoolean(true); private BrowserMobHostNameResolver hostNameResolver; private boolean decompress = true; // not using CopyOnWriteArray because we're WRITE heavy and it is for READ heavy operations // instead doing it the old fashioned way with a synchronized block private final Set<ActiveRequest> activeRequests = new HashSet<ActiveRequest>(); private WildcardMatchingCredentialsProvider credsProvider; private boolean shutdown = false; private AuthType authType; private boolean followRedirects = true; private static final int MAX_REDIRECT = 10; private AtomicInteger requestCounter; public BrowserMobHttpClient(StreamManager streamManager, AtomicInteger requestCounter) { this.requestCounter = requestCounter; SchemeRegistry schemeRegistry = new SchemeRegistry(); hostNameResolver = new BrowserMobHostNameResolver(new Cache(DClass.ANY)); this.socketFactory = new SimulatedSocketFactory(hostNameResolver, streamManager); this.sslSocketFactory = new TrustingSSLSocketFactory(hostNameResolver, streamManager); this.sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier()); schemeRegistry.register(new Scheme("http", 80, socketFactory)); schemeRegistry.register(new Scheme("https", 443, sslSocketFactory)); httpClientConnMgr = new ThreadSafeClientConnManager(schemeRegistry) { @Override public ClientConnectionRequest requestConnection(HttpRoute route, Object state) { final ClientConnectionRequest wrapped = super.requestConnection(route, state); return new ClientConnectionRequest() { @Override public ManagedClientConnection getConnection(long timeout, TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { Date start = new Date(); try { return wrapped.getConnection(timeout, tunit); } finally { RequestInfo.get().blocked(start, new Date()); } } @Override public void abortRequest() { wrapped.abortRequest(); } }; } }; // MOB-338: 30 total connections and 6 connections per host matches the behavior in Firefox 3 httpClientConnMgr.setMaxTotal(30); httpClientConnMgr.setDefaultMaxPerRoute(6); httpClient = new DefaultHttpClient(httpClientConnMgr) { @Override protected HttpRequestExecutor createRequestExecutor() { return new HttpRequestExecutor() { @Override protected HttpResponse doSendRequest(HttpRequest request, HttpClientConnection conn, HttpContext context) throws IOException, HttpException { Date start = new Date(); HttpResponse response = super.doSendRequest(request, conn, context); RequestInfo.get().send(start, new Date()); return response; } @Override protected HttpResponse doReceiveResponse(HttpRequest request, HttpClientConnection conn, HttpContext context) throws HttpException, IOException { Date start = new Date(); HttpResponse response = super.doReceiveResponse(request, conn, context); RequestInfo.get().wait(start, new Date()); return response; } }; } }; credsProvider = new WildcardMatchingCredentialsProvider(); httpClient.setCredentialsProvider(credsProvider); httpClient.addRequestInterceptor(new PreemptiveAuth(), 0); httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true); httpClient.getParams().setParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, Boolean.TRUE); setRetryCount(0); // we always set this to false so it can be handled manually: httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false); HttpClientInterrupter.watch(this); setConnectionTimeout(60000); setSocketOperationTimeout(60000); setRequestTimeout(-1); } public void setRetryCount(int count) { httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(count, false)); } public void remapHost(String source, String target) { hostNameResolver.remap(source, target); } @Deprecated public void addRequestInterceptor(HttpRequestInterceptor i) { httpClient.addRequestInterceptor(i); } public void addRequestInterceptor(RequestInterceptor interceptor) { requestInterceptors.add(interceptor); } @Deprecated public void addResponseInterceptor(HttpResponseInterceptor i) { httpClient.addResponseInterceptor(i); } public void addResponseInterceptor(ResponseInterceptor interceptor) { responseInterceptors.add(interceptor); } public void createCookie(String name, String value, String domain) { createCookie(name, value, domain, null); } public void createCookie(String name, String value, String domain, String path) { BasicClientCookie cookie = new BasicClientCookie(name, value); cookie.setDomain(domain); if (path != null) { cookie.setPath(path); } httpClient.getCookieStore().addCookie(cookie); } public void clearCookies() { httpClient.getCookieStore().clear(); } public Cookie getCookie(String name) { return getCookie(name, null, null); } public Cookie getCookie(String name, String domain) { return getCookie(name, domain, null); } public Cookie getCookie(String name, String domain, String path) { for (Cookie cookie : httpClient.getCookieStore().getCookies()) { if(cookie.getName().equals(name)) { if(domain != null && !domain.equals(cookie.getDomain())) { continue; } if(path != null && !path.equals(cookie.getPath())) { continue; } return cookie; } } return null; } public BrowserMobHttpRequest newPost(String url, org.browsermob.proxy.jetty.http.HttpRequest proxyRequest) { try { URI uri = makeUri(url); return new BrowserMobHttpRequest(new HttpPost(uri), this, -1, captureContent, proxyRequest); } catch (URISyntaxException e) { throw reportBadURI(url, "POST"); } } public BrowserMobHttpRequest newGet(String url, org.browsermob.proxy.jetty.http.HttpRequest proxyRequest) { try { URI uri = makeUri(url); return new BrowserMobHttpRequest(new HttpGet(uri), this, -1, captureContent, proxyRequest); } catch (URISyntaxException e) { throw reportBadURI(url, "GET"); } } public BrowserMobHttpRequest newPut(String url, org.browsermob.proxy.jetty.http.HttpRequest proxyRequest) { try { URI uri = makeUri(url); return new BrowserMobHttpRequest(new HttpPut(uri), this, -1, captureContent, proxyRequest); } catch (Exception e) { throw reportBadURI(url, "PUT"); } } public BrowserMobHttpRequest newDelete(String url, org.browsermob.proxy.jetty.http.HttpRequest proxyRequest) { try { URI uri = makeUri(url); return new BrowserMobHttpRequest(new HttpDelete(uri), this, -1, captureContent, proxyRequest); } catch (URISyntaxException e) { throw reportBadURI(url, "DELETE"); } } public BrowserMobHttpRequest newOptions(String url, org.browsermob.proxy.jetty.http.HttpRequest proxyRequest) { try { URI uri = makeUri(url); return new BrowserMobHttpRequest(new HttpOptions(uri), this, -1, captureContent, proxyRequest); } catch (URISyntaxException e) { throw reportBadURI(url, "OPTIONS"); } } public BrowserMobHttpRequest newHead(String url, org.browsermob.proxy.jetty.http.HttpRequest proxyRequest) { try { URI uri = makeUri(url); return new BrowserMobHttpRequest(new HttpHead(uri), this, -1, captureContent, proxyRequest); } catch (URISyntaxException e) { throw reportBadURI(url, "HEAD"); } } private URI makeUri(String url) throws URISyntaxException { // MOB-120: check for | character and change to correctly escaped %7C url = url.replace(" ", "%20"); url = url.replace(">", "%3C"); url = url.replace("<", "%3E"); url = url.replace("#", "%23"); url = url.replace("{", "%7B"); url = url.replace("}", "%7D"); url = url.replace("|", "%7C"); url = url.replace("\\", "%5C"); url = url.replace("^", "%5E"); url = url.replace("~", "%7E"); url = url.replace("[", "%5B"); url = url.replace("]", "%5D"); url = url.replace("`", "%60"); url = url.replace("\"", "%22"); URI uri = new URI(url); // are we using the default ports for http/https? if so, let's rewrite the URI to make sure the :80 or :443 // is NOT included in the string form the URI. The reason we do this is that in HttpClient 4.0 the Host header // would include a value such as "yahoo.com:80" rather than "yahoo.com". Not sure why this happens but we don't // want it to, and rewriting the URI solves it if ((uri.getPort() == 80 && "http".equals(uri.getScheme())) || (uri.getPort() == 443 && "https".equals(uri.getScheme()))) { // we rewrite the URL with a StringBuilder (vs passing in the components of the URI) because if we were // to pass in these components using the URI's 7-arg constructor query parameters get double escaped (bad!) StringBuilder sb = new StringBuilder(uri.getScheme()).append("://"); if (uri.getRawUserInfo() != null) { sb.append(uri.getRawUserInfo()).append("@"); } sb.append(uri.getHost()); if (uri.getRawPath() != null) { sb.append(uri.getRawPath()); } if (uri.getRawQuery() != null) { sb.append("?").append(uri.getRawQuery()); } if (uri.getRawFragment() != null) { sb.append("#").append(uri.getRawFragment()); } uri = new URI(sb.toString()); } return uri; } private RuntimeException reportBadURI(String url, String method) { if (this.har != null && harPageRef != null) { HarEntry entry = new HarEntry(harPageRef); entry.setTime(0); entry.setRequest(new HarRequest(method, url, "HTTP/1.1")); entry.setResponse(new HarResponse(-998, "Bad URI", "HTTP/1.1")); entry.setTimings(new HarTimings()); har.getLog().addEntry(entry); } throw new BadURIException("Bad URI requested: " + url); } public void checkTimeout() { synchronized (activeRequests) { for (ActiveRequest activeRequest : activeRequests) { activeRequest.checkTimeout(); } } } public BrowserMobHttpResponse execute(BrowserMobHttpRequest req) { if (!allowNewRequests.get()) { throw new RuntimeException("No more requests allowed"); } try { requestCounter.incrementAndGet(); for (RequestInterceptor interceptor : requestInterceptors) { interceptor.process(req); } BrowserMobHttpResponse response = execute(req, 1); for (ResponseInterceptor interceptor : responseInterceptors) { interceptor.process(response); } return response; } finally { requestCounter.decrementAndGet(); } } // //If we were making cake, this would be the filling :) // private BrowserMobHttpResponse execute(BrowserMobHttpRequest req, int depth) { if (depth >= MAX_REDIRECT) { throw new IllegalStateException("Max number of redirects (" + MAX_REDIRECT + ") reached"); } RequestCallback callback = req.getRequestCallback(); HttpRequestBase method = req.getMethod(); String verificationText = req.getVerificationText(); String url = method.getURI().toString(); // save the browser and version if it's not yet been set if (har != null && har.getLog().getBrowser() == null) { Header[] uaHeaders = method.getHeaders("User-Agent"); if (uaHeaders != null && uaHeaders.length > 0) { String userAgent = uaHeaders[0].getValue(); try { // note: this doesn't work for 'Fandango/4.5.1 CFNetwork/548.1.4 Darwin/11.0.0' UASparser p = new CachingOnlineUpdateUASparser(); UserAgentInfo uai = p.parse(userAgent); String name = uai.getUaName(); int lastSpace = name.lastIndexOf(' '); String browser = name.substring(0, lastSpace); String version = name.substring(lastSpace + 1); har.getLog().setBrowser(new HarNameVersion(browser, version)); } catch (IOException e) { // ignore it, it's fine } catch (Exception e) { LOG.warn("Failed to parse user agent string", e); } } } // process any rewrite requests boolean rewrote = false; String newUrl = url; for (RewriteRule rule : rewriteRules) { Matcher matcher = rule.match.matcher(newUrl); newUrl = matcher.replaceAll(rule.replace); rewrote = true; } if (rewrote) { try { method.setURI(new URI(newUrl)); url = newUrl; } catch (URISyntaxException e) { LOG.warn("Could not rewrite url to %s", newUrl); } } // handle whitelist and blacklist entries int mockResponseCode = -1; if (whitelistEntry != null) { boolean found = false; for (Pattern pattern : whitelistEntry.patterns) { if (pattern.matcher(url).matches()) { found = true; break; } } if (!found) { mockResponseCode = whitelistEntry.responseCode; } } if (blacklistEntries != null) { for (BlacklistEntry blacklistEntry : blacklistEntries) { if (blacklistEntry.pattern.matcher(url).matches()) { mockResponseCode = blacklistEntry.responseCode; break; } } } if (!additionalHeaders.isEmpty()) { // Set the additional headers for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); method.removeHeaders(key); method.addHeader(key, value); } } String charSet = "UTF-8"; String responseBody = null; InputStream is = null; int statusCode = -998; long bytes = 0; boolean gzipping = false; boolean contentMatched = true; OutputStream os = req.getOutputStream(); if (os == null) { os = new CappedByteArrayOutputStream(1024 * 1024); // MOB-216 don't buffer more than 1 MB } if (verificationText != null) { contentMatched = false; } Date start = new Date(); // clear out any connection-related information so that it's not stale from previous use of this thread. RequestInfo.clear(url); // link the object up now, before we make the request, so that if we get cut off (ie: favicon.ico request and browser shuts down) // we still have the attempt associated, even if we never got a response HarEntry entry = new HarEntry(harPageRef); entry.setRequest(new HarRequest(method.getMethod(), url, method.getProtocolVersion().getProtocol())); entry.setResponse(new HarResponse(-999, "NO RESPONSE", method.getProtocolVersion().getProtocol())); if (this.har != null && harPageRef != null) { har.getLog().addEntry(entry); } String query = method.getURI().getRawQuery(); if (query != null) { MultiMap<String> params = new MultiMap<String>(); UrlEncoded.decodeTo(query, params, "UTF-8"); for (String k : params.keySet()) { for (Object v : params.getValues(k)) { entry.getRequest().getQueryString().add(new HarNameValuePair(k, (String) v)); } } } String errorMessage = null; HttpResponse response = null; BasicHttpContext ctx = new BasicHttpContext(); ActiveRequest activeRequest = new ActiveRequest(method, ctx, entry.getStartedDateTime()); synchronized (activeRequests) { activeRequests.add(activeRequest); } // for dealing with automatic authentication if (authType == AuthType.NTLM) { // todo: not supported yet //ctx.setAttribute("preemptive-auth", new NTLMScheme(new JCIFSEngine())); } else if (authType == AuthType.BASIC) { ctx.setAttribute("preemptive-auth", new BasicScheme()); } StatusLine statusLine = null; try { // set the User-Agent if it's not already set if (method.getHeaders("User-Agent").length == 0) { method.addHeader("User-Agent", "BrowserMob VU/1.0"); } // was the request mocked out? if (mockResponseCode != -1) { statusCode = mockResponseCode; // TODO: HACKY!! callback.handleHeaders(new Header[]{ new Header(){ @Override public String getName() { return "Content-Type"; } @Override public String getValue() { return "text/plain"; } @Override public HeaderElement[] getElements() throws ParseException { return new HeaderElement[0]; } } }); } else { response = httpClient.execute(method, ctx); statusLine = response.getStatusLine(); statusCode = statusLine.getStatusCode(); if (callback != null) { callback.handleStatusLine(statusLine); callback.handleHeaders(response.getAllHeaders()); } if (response.getEntity() != null) { is = response.getEntity().getContent(); } // check for null (resp 204 can cause HttpClient to return null, which is what Google does with http://clients1.google.com/generate_204) if (is != null) { Header contentEncodingHeader = response.getFirstHeader("Content-Encoding"); if (contentEncodingHeader != null && "gzip".equalsIgnoreCase(contentEncodingHeader.getValue())) { gzipping = true; } // deal with GZIP content! if (decompress && gzipping) { is = new GZIPInputStream(is); } if (captureContent) { // todo - something here? os = new ClonedOutputStream(os); } bytes = copyWithStats(is, os); } } } catch (Exception e) { errorMessage = e.toString(); if (callback != null) { callback.reportError(e); } // only log it if we're not shutdown (otherwise, errors that happen during a shutdown can likely be ignored) if (!shutdown) { LOG.info(String.format("%s when requesting %s", errorMessage, url)); } } finally { // the request is done, get it out of here synchronized (activeRequests) { activeRequests.remove(activeRequest); } if (is != null) { try { is.close(); } catch (IOException e) { // this is OK to ignore } } } // record the response as ended RequestInfo.get().finish(); // set the start time and other timings entry.setStartedDateTime(RequestInfo.get().getStart()); entry.setTimings(RequestInfo.get().getTimings()); entry.setServerIPAddress(RequestInfo.get().getResolvedAddress()); entry.setTime(RequestInfo.get().getTotalTime()); // todo: where you store this in HAR? // obj.setErrorMessage(errorMessage); entry.getResponse().setBodySize(bytes); entry.getResponse().getContent().setSize(bytes); entry.getResponse().setStatus(statusCode); if (statusLine != null) { entry.getResponse().setStatusText(statusLine.getReasonPhrase()); } boolean urlEncoded = false; if (captureHeaders || captureContent) { for (Header header : method.getAllHeaders()) { if (header.getValue() != null && header.getValue().startsWith(URLEncodedUtils.CONTENT_TYPE)) { urlEncoded = true; } entry.getRequest().getHeaders().add(new HarNameValuePair(header.getName(), header.getValue())); } if (response != null) { for (Header header : response.getAllHeaders()) { entry.getResponse().getHeaders().add(new HarNameValuePair(header.getName(), header.getValue())); } } } if (captureContent) { // can we understand the POST data at all? if (method instanceof HttpEntityEnclosingRequestBase && req.getCopy() != null) { HttpEntityEnclosingRequestBase enclosingReq = (HttpEntityEnclosingRequestBase) method; HttpEntity entity = enclosingReq.getEntity(); if (urlEncoded || URLEncodedUtils.isEncoded(entity)) { try { final String content = new String(req.getCopy().toByteArray(), "UTF-8"); if (content != null && content.length() > 0) { List<NameValuePair> result = new ArrayList<NameValuePair>(); URLEncodedUtils.parse(result, new Scanner(content), null); HarPostData data = new HarPostData(); entry.getRequest().setPostData(data); ArrayList<HarPostDataParam> params = new ArrayList<HarPostDataParam>(); data.setParams(params); for (NameValuePair pair : result) { params.add(new HarPostDataParam(pair.getName(), pair.getValue())); } } } catch (Exception e) { LOG.info("Unexpected problem when parsing input copy", e); } } } } //capture request cookies List<Cookie> cookies = (List<Cookie>) ctx.getAttribute("browsermob.http.request.cookies"); if (cookies != null) { for (Cookie c : cookies) { HarCookie hc = toHarCookie(c); entry.getRequest().getCookies().add(hc); } } String contentType = null; if (response != null) { try { Header contentTypeHdr = response.getFirstHeader("Content-Type"); if (contentTypeHdr != null) { contentType = contentTypeHdr.getValue(); entry.getResponse().getContent().setMimeType(contentType); if (captureContent && os != null && os instanceof ClonedOutputStream) { ByteArrayOutputStream copy = ((ClonedOutputStream) os).getOutput(); if (gzipping) { // ok, we need to decompress it before we can put it in the har file try { InputStream temp = new GZIPInputStream(new ByteArrayInputStream(copy.toByteArray())); copy = new ByteArrayOutputStream(); IOUtils.copy(temp, copy); } catch (IOException e) { throw new RuntimeException(e); } } if (contentType != null && contentType.startsWith("text/")) { entry.getResponse().getContent().setText(new String(copy.toByteArray())); } else { entry.getResponse().getContent().setText(Base64.byteArrayToBase64(copy.toByteArray())); } } NameValuePair nvp = contentTypeHdr.getElements()[0].getParameterByName("charset"); if (nvp != null) { charSet = nvp.getValue(); } } if (os instanceof ByteArrayOutputStream) { responseBody = ((ByteArrayOutputStream) os).toString(charSet); if (verificationText != null) { contentMatched = responseBody.contains(verificationText); } } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } //capture response cookies cookies = (List<Cookie>) ctx.getAttribute("browsermob.http.response.cookies"); if (cookies != null) { for (Cookie c : cookies) { HarCookie hc = toHarCookie(c); entry.getResponse().getCookies().add(hc); } } } if (contentType != null) { entry.getResponse().getContent().setMimeType(contentType); } // checking to see if the client is being redirected boolean isRedirect = false; String location = null; if (response != null && statusCode >= 300 && statusCode < 400 && statusCode != 304) { isRedirect = true; // pulling the header for the redirect Header locationHeader = response.getLastHeader("location"); if (locationHeader != null) { location = locationHeader.getValue(); } else if (this.followRedirects) { throw new RuntimeException("Invalid redirect - missing location header"); } } // // Response validation - they only work if we're not following redirects // int expectedStatusCode = req.getExpectedStatusCode(); // if we didn't mock out the actual response code and the expected code isn't what we saw, we have a problem if (mockResponseCode == -1 && expectedStatusCode > -1) { if (this.followRedirects) { throw new RuntimeException("Response validation cannot be used while following redirects"); } if (expectedStatusCode != statusCode) { if (isRedirect) { throw new RuntimeException("Expected status code of " + expectedStatusCode + " but saw " + statusCode + " redirecting to: " + location); } else { throw new RuntimeException("Expected status code of " + expectedStatusCode + " but saw " + statusCode); } } } // Location header check: if (isRedirect && (req.getExpectedLocation() != null)) { if (this.followRedirects) { throw new RuntimeException("Response validation cannot be used while following redirects"); } if (location.compareTo(req.getExpectedLocation()) != 0) { throw new RuntimeException("Expected a redirect to " + req.getExpectedLocation() + " but saw " + location); } } // end of validation logic // basic tail recursion for redirect handling if (isRedirect && this.followRedirects) { // updating location: try { URI redirectUri = new URI(location); URI newUri = method.getURI().resolve(redirectUri); method.setURI(newUri); return execute(req, ++depth); } catch (URISyntaxException e) { LOG.warn("Could not parse URL", e); } } return new BrowserMobHttpResponse(entry, method, response, contentMatched, verificationText, errorMessage, responseBody, contentType, charSet); } public void shutdown() { shutdown = true; abortActiveRequests(); rewriteRules.clear(); credsProvider.clear(); httpClientConnMgr.shutdown(); HttpClientInterrupter.release(this); } public void abortActiveRequests() { allowNewRequests.set(true); synchronized (activeRequests) { for (ActiveRequest activeRequest : activeRequests) { activeRequest.abort(); } activeRequests.clear(); } } public void setHar(Har har) { this.har = har; } public void setHarPageRef(String harPageRef) { this.harPageRef = harPageRef; } public void setRequestTimeout(int requestTimeout) { this.requestTimeout = requestTimeout; } public void setSocketOperationTimeout(int readTimeout) { httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout); } public void setConnectionTimeout(int connectionTimeout) { httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); } public void setFollowRedirects(boolean followRedirects) { this.followRedirects = followRedirects; } public boolean isFollowRedirects() { return followRedirects; } public void autoBasicAuthorization(String domain, String username, String password) { authType = AuthType.BASIC; httpClient.getCredentialsProvider().setCredentials( new AuthScope(domain, -1), new UsernamePasswordCredentials(username, password)); } public void autoNTLMAuthorization(String domain, String username, String password) { authType = AuthType.NTLM; httpClient.getCredentialsProvider().setCredentials( new AuthScope(domain, -1), new NTCredentials(username, password, "workstation", domain)); } public void rewriteUrl(String match, String replace) { rewriteRules.add(new RewriteRule(match, replace)); } // this method is provided for backwards compatibility before we renamed it to // blacklistRequests (note the plural) public void blacklistRequest(String pattern, int responseCode) { blacklistRequests(pattern, responseCode); } public void blacklistRequests(String pattern, int responseCode) { if (blacklistEntries == null) { blacklistEntries = new CopyOnWriteArrayList<BlacklistEntry>(); } blacklistEntries.add(new BlacklistEntry(pattern, responseCode)); } public void whitelistRequests(String[] patterns, int responseCode) { whitelistEntry = new WhitelistEntry(patterns, responseCode); } public void addHeader(String name, String value) { additionalHeaders.put(name, value); } public void prepareForBrowser() { //save request and reponse cookies to the context httpClient.addRequestInterceptor(new RequestCookiesInterceptor()); httpClient.addResponseInterceptor(new ResponseCookiesInterceptor()); decompress = false; setFollowRedirects(false); } public String remappedHost(String host) { return hostNameResolver.remapping(host); } public List<String> originalHosts(String host) { return hostNameResolver.original(host); } public Har getHar() { return har; } public void setCaptureHeaders(boolean captureHeaders) { this.captureHeaders = captureHeaders; } public void setCaptureContent(boolean captureContent) { this.captureContent = captureContent; } public void setHttpProxy(String httpProxy) { String host = httpProxy.split(":")[0]; Integer port = Integer.parseInt(httpProxy.split(":")[1]); HttpHost proxy = new HttpHost(host, port); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy); } static class PreemptiveAuth implements HttpRequestInterceptor { public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE); // If no auth scheme avaialble yet, try to initialize it preemptively if (authState.getAuthScheme() == null) { AuthScheme authScheme = (AuthScheme) context.getAttribute( "preemptive-auth"); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute( ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST); if (authScheme != null) { Credentials creds = credsProvider.getCredentials( new AuthScope( targetHost.getHostName(), targetHost.getPort())); if (creds != null) { authState.setAuthScheme(authScheme); authState.setCredentials(creds); } } } } } private HarCookie toHarCookie(Cookie c) { HarCookie hc = new HarCookie(); hc.setName(c.getName()); hc.setPath(c.getPath()); hc.setValue(c.getValue()); hc.setDomain(c.getDomain()); hc.setExpires(c.getExpiryDate()); return hc; } class ActiveRequest { HttpRequestBase request; BasicHttpContext ctx; Date start; ActiveRequest(HttpRequestBase request, BasicHttpContext ctx, Date start) { this.request = request; this.ctx = ctx; this.start = start; } void checkTimeout() { if (requestTimeout != -1) { if (request != null && start != null && new Date(System.currentTimeMillis() - requestTimeout).after(start)) { LOG.info("Aborting request to %s after it failed to complete in %d ms", request.getURI().toString(), requestTimeout); abort(); } } } public void abort() { request.abort(); // try to close the connection? is this necessary? unclear based on preliminary debugging of HttpClient, but // it doesn't seem to hurt to try HttpConnection conn = (HttpConnection) ctx.getAttribute("http.connection"); if (conn != null) { try { conn.close(); } catch (IOException e) { // this is fine, we're shutting it down anyway } } } } private class WhitelistEntry { private List<Pattern> patterns = new CopyOnWriteArrayList<Pattern>(); private int responseCode; private WhitelistEntry(String[] patterns, int responseCode) { for (String pattern : patterns) { this.patterns.add(Pattern.compile(pattern)); } this.responseCode = responseCode; } } private class BlacklistEntry { private Pattern pattern; private int responseCode; private BlacklistEntry(String pattern, int responseCode) { this.pattern = Pattern.compile(pattern); this.responseCode = responseCode; } } private class RewriteRule { private Pattern match; private String replace; private RewriteRule(String match, String replace) { this.match = Pattern.compile(match); this.replace = replace; } } private enum AuthType { NONE, BASIC, NTLM } public void clearDNSCache() { this.hostNameResolver.clearCache(); } public void setDNSCacheTimeout(int timeout) { this.hostNameResolver.setCacheTimeout(timeout); } public static long copyWithStats(InputStream is, OutputStream os) throws IOException { long bytesCopied = 0; byte[] buffer = new byte[BUFFER]; int length; try { // read the first byte int firstByte = is.read(); if (firstByte == -1) { return 0; } os.write(firstByte); bytesCopied++; do { length = is.read(buffer, 0, BUFFER); if (length != -1) { bytesCopied += length; os.write(buffer, 0, length); os.flush(); } } while (length != -1); } finally { try { is.close(); } catch (IOException e) { // ok to ignore } try { os.close(); } catch (IOException e) { // ok to ignore } } return bytesCopied; } }
src/main/java/org/browsermob/proxy/http/BrowserMobHttpClient.java
package org.browsermob.proxy.http; import cz.mallat.uasparser.CachingOnlineUpdateUASparser; import cz.mallat.uasparser.UASparser; import cz.mallat.uasparser.UserAgentInfo; import org.apache.http.*; import org.apache.http.HttpConnection; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.auth.*; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.*; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.protocol.ClientContext; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.ClientConnectionRequest; import org.apache.http.conn.ConnectionPoolTimeoutException; import org.apache.http.conn.ManagedClientConnection; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.cookie.Cookie; import org.apache.http.cookie.params.CookieSpecPNames; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestExecutor; import org.browsermob.core.har.*; import org.browsermob.proxy.util.*; import org.java_bandwidthlimiter.StreamManager; import org.eclipse.jetty.util.MultiMap; import org.eclipse.jetty.util.UrlEncoded; import org.xbill.DNS.Cache; import org.xbill.DNS.DClass; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class BrowserMobHttpClient { private static final int BUFFER = 4096; private static final Log LOG = new Log(); private Har har; private String harPageRef; private boolean captureHeaders; private boolean captureContent; private SimulatedSocketFactory socketFactory; private TrustingSSLSocketFactory sslSocketFactory; private ThreadSafeClientConnManager httpClientConnMgr; private DefaultHttpClient httpClient; private List<BlacklistEntry> blacklistEntries = null; private WhitelistEntry whitelistEntry = null; private List<RewriteRule> rewriteRules = new CopyOnWriteArrayList<RewriteRule>(); private List<RequestInterceptor> requestInterceptors = new CopyOnWriteArrayList<RequestInterceptor>(); private List<ResponseInterceptor> responseInterceptors = new CopyOnWriteArrayList<ResponseInterceptor>(); private HashMap<String, String> additionalHeaders = new LinkedHashMap<String, String>(); private int requestTimeout; private AtomicBoolean allowNewRequests = new AtomicBoolean(true); private BrowserMobHostNameResolver hostNameResolver; private boolean decompress = true; // not using CopyOnWriteArray because we're WRITE heavy and it is for READ heavy operations // instead doing it the old fashioned way with a synchronized block private final Set<ActiveRequest> activeRequests = new HashSet<ActiveRequest>(); private WildcardMatchingCredentialsProvider credsProvider; private boolean shutdown = false; private AuthType authType; private boolean followRedirects = true; private static final int MAX_REDIRECT = 10; private AtomicInteger requestCounter; public BrowserMobHttpClient(StreamManager streamManager, AtomicInteger requestCounter) { this.requestCounter = requestCounter; SchemeRegistry schemeRegistry = new SchemeRegistry(); hostNameResolver = new BrowserMobHostNameResolver(new Cache(DClass.ANY)); this.socketFactory = new SimulatedSocketFactory(hostNameResolver, streamManager); this.sslSocketFactory = new TrustingSSLSocketFactory(hostNameResolver, streamManager); this.sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier()); schemeRegistry.register(new Scheme("http", 80, socketFactory)); schemeRegistry.register(new Scheme("https", 443, sslSocketFactory)); httpClientConnMgr = new ThreadSafeClientConnManager(schemeRegistry) { @Override public ClientConnectionRequest requestConnection(HttpRoute route, Object state) { final ClientConnectionRequest wrapped = super.requestConnection(route, state); return new ClientConnectionRequest() { @Override public ManagedClientConnection getConnection(long timeout, TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { Date start = new Date(); try { return wrapped.getConnection(timeout, tunit); } finally { RequestInfo.get().blocked(start, new Date()); } } @Override public void abortRequest() { wrapped.abortRequest(); } }; } }; // MOB-338: 30 total connections and 6 connections per host matches the behavior in Firefox 3 httpClientConnMgr.setMaxTotal(30); httpClientConnMgr.setDefaultMaxPerRoute(6); httpClient = new DefaultHttpClient(httpClientConnMgr) { @Override protected HttpRequestExecutor createRequestExecutor() { return new HttpRequestExecutor() { @Override protected HttpResponse doSendRequest(HttpRequest request, HttpClientConnection conn, HttpContext context) throws IOException, HttpException { Date start = new Date(); HttpResponse response = super.doSendRequest(request, conn, context); RequestInfo.get().send(start, new Date()); return response; } @Override protected HttpResponse doReceiveResponse(HttpRequest request, HttpClientConnection conn, HttpContext context) throws HttpException, IOException { Date start = new Date(); HttpResponse response = super.doReceiveResponse(request, conn, context); RequestInfo.get().wait(start, new Date()); return response; } }; } }; credsProvider = new WildcardMatchingCredentialsProvider(); httpClient.setCredentialsProvider(credsProvider); httpClient.addRequestInterceptor(new PreemptiveAuth(), 0); httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true); httpClient.getParams().setParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, Boolean.TRUE); setRetryCount(0); // we always set this to false so it can be handled manually: httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false); HttpClientInterrupter.watch(this); setConnectionTimeout(60000); setSocketOperationTimeout(60000); setRequestTimeout(-1); } public void setRetryCount(int count) { httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(count, false)); } public void remapHost(String source, String target) { hostNameResolver.remap(source, target); } @Deprecated public void addRequestInterceptor(HttpRequestInterceptor i) { httpClient.addRequestInterceptor(i); } public void addRequestInterceptor(RequestInterceptor interceptor) { requestInterceptors.add(interceptor); } @Deprecated public void addResponseInterceptor(HttpResponseInterceptor i) { httpClient.addResponseInterceptor(i); } public void addResponseInterceptor(ResponseInterceptor interceptor) { responseInterceptors.add(interceptor); } public void createCookie(String name, String value, String domain) { createCookie(name, value, domain, null); } public void createCookie(String name, String value, String domain, String path) { BasicClientCookie cookie = new BasicClientCookie(name, value); cookie.setDomain(domain); if (path != null) { cookie.setPath(path); } httpClient.getCookieStore().addCookie(cookie); } public void clearCookies() { httpClient.getCookieStore().clear(); } public Cookie getCookie(String name) { return getCookie(name, null, null); } public Cookie getCookie(String name, String domain) { return getCookie(name, domain, null); } public Cookie getCookie(String name, String domain, String path) { for (Cookie cookie : httpClient.getCookieStore().getCookies()) { if(cookie.getName().equals(name)) { if(domain != null && !domain.equals(cookie.getDomain())) { continue; } if(path != null && !path.equals(cookie.getPath())) { continue; } return cookie; } } return null; } public BrowserMobHttpRequest newPost(String url, org.browsermob.proxy.jetty.http.HttpRequest proxyRequest) { try { URI uri = makeUri(url); return new BrowserMobHttpRequest(new HttpPost(uri), this, -1, captureContent, proxyRequest); } catch (URISyntaxException e) { throw reportBadURI(url, "POST"); } } public BrowserMobHttpRequest newGet(String url, org.browsermob.proxy.jetty.http.HttpRequest proxyRequest) { try { URI uri = makeUri(url); return new BrowserMobHttpRequest(new HttpGet(uri), this, -1, captureContent, proxyRequest); } catch (URISyntaxException e) { throw reportBadURI(url, "GET"); } } public BrowserMobHttpRequest newPut(String url, org.browsermob.proxy.jetty.http.HttpRequest proxyRequest) { try { URI uri = makeUri(url); return new BrowserMobHttpRequest(new HttpPut(uri), this, -1, captureContent, proxyRequest); } catch (Exception e) { throw reportBadURI(url, "PUT"); } } public BrowserMobHttpRequest newDelete(String url, org.browsermob.proxy.jetty.http.HttpRequest proxyRequest) { try { URI uri = makeUri(url); return new BrowserMobHttpRequest(new HttpDelete(uri), this, -1, captureContent, proxyRequest); } catch (URISyntaxException e) { throw reportBadURI(url, "DELETE"); } } public BrowserMobHttpRequest newOptions(String url, org.browsermob.proxy.jetty.http.HttpRequest proxyRequest) { try { URI uri = makeUri(url); return new BrowserMobHttpRequest(new HttpOptions(uri), this, -1, captureContent, proxyRequest); } catch (URISyntaxException e) { throw reportBadURI(url, "OPTIONS"); } } public BrowserMobHttpRequest newHead(String url, org.browsermob.proxy.jetty.http.HttpRequest proxyRequest) { try { URI uri = makeUri(url); return new BrowserMobHttpRequest(new HttpHead(uri), this, -1, captureContent, proxyRequest); } catch (URISyntaxException e) { throw reportBadURI(url, "HEAD"); } } private URI makeUri(String url) throws URISyntaxException { // MOB-120: check for | character and change to correctly escaped %7C url = url.replace(" ", "%20"); url = url.replace(">", "%3C"); url = url.replace("<", "%3E"); url = url.replace("#", "%23"); url = url.replace("{", "%7B"); url = url.replace("}", "%7D"); url = url.replace("|", "%7C"); url = url.replace("\\", "%5C"); url = url.replace("^", "%5E"); url = url.replace("~", "%7E"); url = url.replace("[", "%5B"); url = url.replace("]", "%5D"); url = url.replace("`", "%60"); url = url.replace("\"", "%22"); URI uri = new URI(url); // are we using the default ports for http/https? if so, let's rewrite the URI to make sure the :80 or :443 // is NOT included in the string form the URI. The reason we do this is that in HttpClient 4.0 the Host header // would include a value such as "yahoo.com:80" rather than "yahoo.com". Not sure why this happens but we don't // want it to, and rewriting the URI solves it if ((uri.getPort() == 80 && "http".equals(uri.getScheme())) || (uri.getPort() == 443 && "https".equals(uri.getScheme()))) { // we rewrite the URL with a StringBuilder (vs passing in the components of the URI) because if we were // to pass in these components using the URI's 7-arg constructor query parameters get double escaped (bad!) StringBuilder sb = new StringBuilder(uri.getScheme()).append("://"); if (uri.getRawUserInfo() != null) { sb.append(uri.getRawUserInfo()).append("@"); } sb.append(uri.getHost()); if (uri.getRawPath() != null) { sb.append(uri.getRawPath()); } if (uri.getRawQuery() != null) { sb.append("?").append(uri.getRawQuery()); } if (uri.getRawFragment() != null) { sb.append("#").append(uri.getRawFragment()); } uri = new URI(sb.toString()); } return uri; } private RuntimeException reportBadURI(String url, String method) { if (this.har != null && harPageRef != null) { HarEntry entry = new HarEntry(harPageRef); entry.setTime(0); entry.setRequest(new HarRequest(method, url, "HTTP/1.1")); entry.setResponse(new HarResponse(-998, "Bad URI", "HTTP/1.1")); entry.setTimings(new HarTimings()); har.getLog().addEntry(entry); } throw new BadURIException("Bad URI requested: " + url); } public void checkTimeout() { synchronized (activeRequests) { for (ActiveRequest activeRequest : activeRequests) { activeRequest.checkTimeout(); } } } public BrowserMobHttpResponse execute(BrowserMobHttpRequest req) { if (!allowNewRequests.get()) { throw new RuntimeException("No more requests allowed"); } try { requestCounter.incrementAndGet(); for (RequestInterceptor interceptor : requestInterceptors) { interceptor.process(req); } BrowserMobHttpResponse response = execute(req, 1); for (ResponseInterceptor interceptor : responseInterceptors) { interceptor.process(response); } return response; } finally { requestCounter.decrementAndGet(); } } // //If we were making cake, this would be the filling :) // private BrowserMobHttpResponse execute(BrowserMobHttpRequest req, int depth) { if (depth >= MAX_REDIRECT) { throw new IllegalStateException("Max number of redirects (" + MAX_REDIRECT + ") reached"); } RequestCallback callback = req.getRequestCallback(); HttpRequestBase method = req.getMethod(); String verificationText = req.getVerificationText(); String url = method.getURI().toString(); // save the browser and version if it's not yet been set if (har != null && har.getLog().getBrowser() == null) { Header[] uaHeaders = method.getHeaders("User-Agent"); if (uaHeaders != null && uaHeaders.length > 0) { String userAgent = uaHeaders[0].getValue(); try { // note: this doesn't work for 'Fandango/4.5.1 CFNetwork/548.1.4 Darwin/11.0.0' UASparser p = new CachingOnlineUpdateUASparser(); UserAgentInfo uai = p.parse(userAgent); String name = uai.getUaName(); int lastSpace = name.lastIndexOf(' '); String browser = name.substring(0, lastSpace); String version = name.substring(lastSpace + 1); har.getLog().setBrowser(new HarNameVersion(browser, version)); } catch (IOException e) { // ignore it, it's fine } catch (Exception e) { LOG.warn("Failed to parse user agent string", e); } } } // process any rewrite requests boolean rewrote = false; String newUrl = url; for (RewriteRule rule : rewriteRules) { Matcher matcher = rule.match.matcher(newUrl); newUrl = matcher.replaceAll(rule.replace); rewrote = true; } if (rewrote) { try { method.setURI(new URI(newUrl)); url = newUrl; } catch (URISyntaxException e) { LOG.warn("Could not rewrite url to %s", newUrl); } } // handle whitelist and blacklist entries int mockResponseCode = -1; if (whitelistEntry != null) { boolean found = false; for (Pattern pattern : whitelistEntry.patterns) { if (pattern.matcher(url).matches()) { found = true; break; } } if (!found) { mockResponseCode = whitelistEntry.responseCode; } } if (blacklistEntries != null) { for (BlacklistEntry blacklistEntry : blacklistEntries) { if (blacklistEntry.pattern.matcher(url).matches()) { mockResponseCode = blacklistEntry.responseCode; break; } } } if (!additionalHeaders.isEmpty()) { // Set the additional headers for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); method.removeHeaders(key); method.addHeader(key, value); } } String charSet = "UTF-8"; String responseBody = null; InputStream is = null; int statusCode = -998; long bytes = 0; boolean gzipping = false; boolean contentMatched = true; OutputStream os = req.getOutputStream(); if (os == null) { os = new CappedByteArrayOutputStream(1024 * 1024); // MOB-216 don't buffer more than 1 MB } if (verificationText != null) { contentMatched = false; } Date start = new Date(); // clear out any connection-related information so that it's not stale from previous use of this thread. RequestInfo.clear(url); // link the object up now, before we make the request, so that if we get cut off (ie: favicon.ico request and browser shuts down) // we still have the attempt associated, even if we never got a response HarEntry entry = new HarEntry(harPageRef); entry.setRequest(new HarRequest(method.getMethod(), url, method.getProtocolVersion().getProtocol())); entry.setResponse(new HarResponse(-999, "NO RESPONSE", method.getProtocolVersion().getProtocol())); if (this.har != null && harPageRef != null) { har.getLog().addEntry(entry); } String query = method.getURI().getQuery(); if (query != null) { MultiMap<String> params = new MultiMap<String>(); UrlEncoded.decodeTo(query, params, "UTF-8"); for (String k : params.keySet()) { for (Object v : params.getValues(k)) { entry.getRequest().getQueryString().add(new HarNameValuePair(k, (String) v)); } } } String errorMessage = null; HttpResponse response = null; BasicHttpContext ctx = new BasicHttpContext(); ActiveRequest activeRequest = new ActiveRequest(method, ctx, entry.getStartedDateTime()); synchronized (activeRequests) { activeRequests.add(activeRequest); } // for dealing with automatic authentication if (authType == AuthType.NTLM) { // todo: not supported yet //ctx.setAttribute("preemptive-auth", new NTLMScheme(new JCIFSEngine())); } else if (authType == AuthType.BASIC) { ctx.setAttribute("preemptive-auth", new BasicScheme()); } StatusLine statusLine = null; try { // set the User-Agent if it's not already set if (method.getHeaders("User-Agent").length == 0) { method.addHeader("User-Agent", "BrowserMob VU/1.0"); } // was the request mocked out? if (mockResponseCode != -1) { statusCode = mockResponseCode; // TODO: HACKY!! callback.handleHeaders(new Header[]{ new Header(){ @Override public String getName() { return "Content-Type"; } @Override public String getValue() { return "text/plain"; } @Override public HeaderElement[] getElements() throws ParseException { return new HeaderElement[0]; } } }); } else { response = httpClient.execute(method, ctx); statusLine = response.getStatusLine(); statusCode = statusLine.getStatusCode(); if (callback != null) { callback.handleStatusLine(statusLine); callback.handleHeaders(response.getAllHeaders()); } if (response.getEntity() != null) { is = response.getEntity().getContent(); } // check for null (resp 204 can cause HttpClient to return null, which is what Google does with http://clients1.google.com/generate_204) if (is != null) { Header contentEncodingHeader = response.getFirstHeader("Content-Encoding"); if (contentEncodingHeader != null && "gzip".equalsIgnoreCase(contentEncodingHeader.getValue())) { gzipping = true; } // deal with GZIP content! if (decompress && gzipping) { is = new GZIPInputStream(is); } if (captureContent) { // todo - something here? os = new ClonedOutputStream(os); } bytes = copyWithStats(is, os); } } } catch (Exception e) { errorMessage = e.toString(); if (callback != null) { callback.reportError(e); } // only log it if we're not shutdown (otherwise, errors that happen during a shutdown can likely be ignored) if (!shutdown) { LOG.info(String.format("%s when requesting %s", errorMessage, url)); } } finally { // the request is done, get it out of here synchronized (activeRequests) { activeRequests.remove(activeRequest); } if (is != null) { try { is.close(); } catch (IOException e) { // this is OK to ignore } } } // record the response as ended RequestInfo.get().finish(); // set the start time and other timings entry.setStartedDateTime(RequestInfo.get().getStart()); entry.setTimings(RequestInfo.get().getTimings()); entry.setServerIPAddress(RequestInfo.get().getResolvedAddress()); entry.setTime(RequestInfo.get().getTotalTime()); // todo: where you store this in HAR? // obj.setErrorMessage(errorMessage); entry.getResponse().setBodySize(bytes); entry.getResponse().getContent().setSize(bytes); entry.getResponse().setStatus(statusCode); if (statusLine != null) { entry.getResponse().setStatusText(statusLine.getReasonPhrase()); } boolean urlEncoded = false; if (captureHeaders || captureContent) { for (Header header : method.getAllHeaders()) { if (header.getValue() != null && header.getValue().startsWith(URLEncodedUtils.CONTENT_TYPE)) { urlEncoded = true; } entry.getRequest().getHeaders().add(new HarNameValuePair(header.getName(), header.getValue())); } if (response != null) { for (Header header : response.getAllHeaders()) { entry.getResponse().getHeaders().add(new HarNameValuePair(header.getName(), header.getValue())); } } } if (captureContent) { // can we understand the POST data at all? if (method instanceof HttpEntityEnclosingRequestBase && req.getCopy() != null) { HttpEntityEnclosingRequestBase enclosingReq = (HttpEntityEnclosingRequestBase) method; HttpEntity entity = enclosingReq.getEntity(); if (urlEncoded || URLEncodedUtils.isEncoded(entity)) { try { final String content = new String(req.getCopy().toByteArray(), "UTF-8"); if (content != null && content.length() > 0) { List<NameValuePair> result = new ArrayList<NameValuePair>(); URLEncodedUtils.parse(result, new Scanner(content), null); HarPostData data = new HarPostData(); entry.getRequest().setPostData(data); ArrayList<HarPostDataParam> params = new ArrayList<HarPostDataParam>(); data.setParams(params); for (NameValuePair pair : result) { params.add(new HarPostDataParam(pair.getName(), pair.getValue())); } } } catch (Exception e) { LOG.info("Unexpected problem when parsing input copy", e); } } } } //capture request cookies List<Cookie> cookies = (List<Cookie>) ctx.getAttribute("browsermob.http.request.cookies"); if (cookies != null) { for (Cookie c : cookies) { HarCookie hc = toHarCookie(c); entry.getRequest().getCookies().add(hc); } } String contentType = null; if (response != null) { try { Header contentTypeHdr = response.getFirstHeader("Content-Type"); if (contentTypeHdr != null) { contentType = contentTypeHdr.getValue(); entry.getResponse().getContent().setMimeType(contentType); if (captureContent && os != null && os instanceof ClonedOutputStream) { ByteArrayOutputStream copy = ((ClonedOutputStream) os).getOutput(); if (gzipping) { // ok, we need to decompress it before we can put it in the har file try { InputStream temp = new GZIPInputStream(new ByteArrayInputStream(copy.toByteArray())); copy = new ByteArrayOutputStream(); IOUtils.copy(temp, copy); } catch (IOException e) { throw new RuntimeException(e); } } if (contentType != null && contentType.startsWith("text/")) { entry.getResponse().getContent().setText(new String(copy.toByteArray())); } else { entry.getResponse().getContent().setText(Base64.byteArrayToBase64(copy.toByteArray())); } } NameValuePair nvp = contentTypeHdr.getElements()[0].getParameterByName("charset"); if (nvp != null) { charSet = nvp.getValue(); } } if (os instanceof ByteArrayOutputStream) { responseBody = ((ByteArrayOutputStream) os).toString(charSet); if (verificationText != null) { contentMatched = responseBody.contains(verificationText); } } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } //capture response cookies cookies = (List<Cookie>) ctx.getAttribute("browsermob.http.response.cookies"); if (cookies != null) { for (Cookie c : cookies) { HarCookie hc = toHarCookie(c); entry.getResponse().getCookies().add(hc); } } } if (contentType != null) { entry.getResponse().getContent().setMimeType(contentType); } // checking to see if the client is being redirected boolean isRedirect = false; String location = null; if (response != null && statusCode >= 300 && statusCode < 400 && statusCode != 304) { isRedirect = true; // pulling the header for the redirect Header locationHeader = response.getLastHeader("location"); if (locationHeader != null) { location = locationHeader.getValue(); } else if (this.followRedirects) { throw new RuntimeException("Invalid redirect - missing location header"); } } // // Response validation - they only work if we're not following redirects // int expectedStatusCode = req.getExpectedStatusCode(); // if we didn't mock out the actual response code and the expected code isn't what we saw, we have a problem if (mockResponseCode == -1 && expectedStatusCode > -1) { if (this.followRedirects) { throw new RuntimeException("Response validation cannot be used while following redirects"); } if (expectedStatusCode != statusCode) { if (isRedirect) { throw new RuntimeException("Expected status code of " + expectedStatusCode + " but saw " + statusCode + " redirecting to: " + location); } else { throw new RuntimeException("Expected status code of " + expectedStatusCode + " but saw " + statusCode); } } } // Location header check: if (isRedirect && (req.getExpectedLocation() != null)) { if (this.followRedirects) { throw new RuntimeException("Response validation cannot be used while following redirects"); } if (location.compareTo(req.getExpectedLocation()) != 0) { throw new RuntimeException("Expected a redirect to " + req.getExpectedLocation() + " but saw " + location); } } // end of validation logic // basic tail recursion for redirect handling if (isRedirect && this.followRedirects) { // updating location: try { URI redirectUri = new URI(location); URI newUri = method.getURI().resolve(redirectUri); method.setURI(newUri); return execute(req, ++depth); } catch (URISyntaxException e) { LOG.warn("Could not parse URL", e); } } return new BrowserMobHttpResponse(entry, method, response, contentMatched, verificationText, errorMessage, responseBody, contentType, charSet); } public void shutdown() { shutdown = true; abortActiveRequests(); rewriteRules.clear(); credsProvider.clear(); httpClientConnMgr.shutdown(); HttpClientInterrupter.release(this); } public void abortActiveRequests() { allowNewRequests.set(true); synchronized (activeRequests) { for (ActiveRequest activeRequest : activeRequests) { activeRequest.abort(); } activeRequests.clear(); } } public void setHar(Har har) { this.har = har; } public void setHarPageRef(String harPageRef) { this.harPageRef = harPageRef; } public void setRequestTimeout(int requestTimeout) { this.requestTimeout = requestTimeout; } public void setSocketOperationTimeout(int readTimeout) { httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout); } public void setConnectionTimeout(int connectionTimeout) { httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); } public void setFollowRedirects(boolean followRedirects) { this.followRedirects = followRedirects; } public boolean isFollowRedirects() { return followRedirects; } public void autoBasicAuthorization(String domain, String username, String password) { authType = AuthType.BASIC; httpClient.getCredentialsProvider().setCredentials( new AuthScope(domain, -1), new UsernamePasswordCredentials(username, password)); } public void autoNTLMAuthorization(String domain, String username, String password) { authType = AuthType.NTLM; httpClient.getCredentialsProvider().setCredentials( new AuthScope(domain, -1), new NTCredentials(username, password, "workstation", domain)); } public void rewriteUrl(String match, String replace) { rewriteRules.add(new RewriteRule(match, replace)); } // this method is provided for backwards compatibility before we renamed it to // blacklistRequests (note the plural) public void blacklistRequest(String pattern, int responseCode) { blacklistRequests(pattern, responseCode); } public void blacklistRequests(String pattern, int responseCode) { if (blacklistEntries == null) { blacklistEntries = new CopyOnWriteArrayList<BlacklistEntry>(); } blacklistEntries.add(new BlacklistEntry(pattern, responseCode)); } public void whitelistRequests(String[] patterns, int responseCode) { whitelistEntry = new WhitelistEntry(patterns, responseCode); } public void addHeader(String name, String value) { additionalHeaders.put(name, value); } public void prepareForBrowser() { //save request and reponse cookies to the context httpClient.addRequestInterceptor(new RequestCookiesInterceptor()); httpClient.addResponseInterceptor(new ResponseCookiesInterceptor()); decompress = false; setFollowRedirects(false); } public String remappedHost(String host) { return hostNameResolver.remapping(host); } public List<String> originalHosts(String host) { return hostNameResolver.original(host); } public Har getHar() { return har; } public void setCaptureHeaders(boolean captureHeaders) { this.captureHeaders = captureHeaders; } public void setCaptureContent(boolean captureContent) { this.captureContent = captureContent; } public void setHttpProxy(String httpProxy) { String host = httpProxy.split(":")[0]; Integer port = Integer.parseInt(httpProxy.split(":")[1]); HttpHost proxy = new HttpHost(host, port); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy); } static class PreemptiveAuth implements HttpRequestInterceptor { public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE); // If no auth scheme avaialble yet, try to initialize it preemptively if (authState.getAuthScheme() == null) { AuthScheme authScheme = (AuthScheme) context.getAttribute( "preemptive-auth"); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute( ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST); if (authScheme != null) { Credentials creds = credsProvider.getCredentials( new AuthScope( targetHost.getHostName(), targetHost.getPort())); if (creds != null) { authState.setAuthScheme(authScheme); authState.setCredentials(creds); } } } } } private HarCookie toHarCookie(Cookie c) { HarCookie hc = new HarCookie(); hc.setName(c.getName()); hc.setPath(c.getPath()); hc.setValue(c.getValue()); hc.setDomain(c.getDomain()); hc.setExpires(c.getExpiryDate()); return hc; } class ActiveRequest { HttpRequestBase request; BasicHttpContext ctx; Date start; ActiveRequest(HttpRequestBase request, BasicHttpContext ctx, Date start) { this.request = request; this.ctx = ctx; this.start = start; } void checkTimeout() { if (requestTimeout != -1) { if (request != null && start != null && new Date(System.currentTimeMillis() - requestTimeout).after(start)) { LOG.info("Aborting request to %s after it failed to complete in %d ms", request.getURI().toString(), requestTimeout); abort(); } } } public void abort() { request.abort(); // try to close the connection? is this necessary? unclear based on preliminary debugging of HttpClient, but // it doesn't seem to hurt to try HttpConnection conn = (HttpConnection) ctx.getAttribute("http.connection"); if (conn != null) { try { conn.close(); } catch (IOException e) { // this is fine, we're shutting it down anyway } } } } private class WhitelistEntry { private List<Pattern> patterns = new CopyOnWriteArrayList<Pattern>(); private int responseCode; private WhitelistEntry(String[] patterns, int responseCode) { for (String pattern : patterns) { this.patterns.add(Pattern.compile(pattern)); } this.responseCode = responseCode; } } private class BlacklistEntry { private Pattern pattern; private int responseCode; private BlacklistEntry(String pattern, int responseCode) { this.pattern = Pattern.compile(pattern); this.responseCode = responseCode; } } private class RewriteRule { private Pattern match; private String replace; private RewriteRule(String match, String replace) { this.match = Pattern.compile(match); this.replace = replace; } } private enum AuthType { NONE, BASIC, NTLM } public void clearDNSCache() { this.hostNameResolver.clearCache(); } public void setDNSCacheTimeout(int timeout) { this.hostNameResolver.setCacheTimeout(timeout); } public static long copyWithStats(InputStream is, OutputStream os) throws IOException { long bytesCopied = 0; byte[] buffer = new byte[BUFFER]; int length; try { // read the first byte int firstByte = is.read(); if (firstByte == -1) { return 0; } os.write(firstByte); bytesCopied++; do { length = is.read(buffer, 0, BUFFER); if (length != -1) { bytesCopied += length; os.write(buffer, 0, length); os.flush(); } } while (length != -1); } finally { try { is.close(); } catch (IOException e) { // ok to ignore } try { os.close(); } catch (IOException e) { // ok to ignore } } return bytesCopied; } }
fix for double URL decoded query string
src/main/java/org/browsermob/proxy/http/BrowserMobHttpClient.java
fix for double URL decoded query string
<ide><path>rc/main/java/org/browsermob/proxy/http/BrowserMobHttpClient.java <ide> har.getLog().addEntry(entry); <ide> } <ide> <del> String query = method.getURI().getQuery(); <add> String query = method.getURI().getRawQuery(); <ide> if (query != null) { <ide> MultiMap<String> params = new MultiMap<String>(); <ide> UrlEncoded.decodeTo(query, params, "UTF-8");
Java
mit
error: pathspec 'EpicsUtil/src/main/java/org/epics/util/time/package-info.java' did not match any file(s) known to git
5a81e55446264aedcb4a4ae6f8cdf9b747e20a17
1
berryma4/diirt,berryma4/diirt,diirt/diirt,richardfearn/diirt,berryma4/diirt,berryma4/diirt,diirt/diirt,richardfearn/diirt,ControlSystemStudio/diirt,ControlSystemStudio/diirt,richardfearn/diirt,ControlSystemStudio/diirt,ControlSystemStudio/diirt,diirt/diirt,diirt/diirt
/* * Copyright 2011 Brookhaven National Laboratory * All rights reserved. Use is subject to license terms. */ /** * Contains basic common classes to handle time at nanosecond precision. * <p> * <h3>JSR 310 compatibility</h3> * Java 8 will introduce a better time definition that is going to be very * similar to these class. That effort is unfortunately too unstable to use * directly. When it will be released, the plan is to phase out this package * and use the standard where possible. Same definitions and conventions * are taken from JSR 310 to make future conversion easier. * */ package org.epics.util.time;
EpicsUtil/src/main/java/org/epics/util/time/package-info.java
Adding package documentation.
EpicsUtil/src/main/java/org/epics/util/time/package-info.java
Adding package documentation.
<ide><path>picsUtil/src/main/java/org/epics/util/time/package-info.java <add>/* <add> * Copyright 2011 Brookhaven National Laboratory <add> * All rights reserved. Use is subject to license terms. <add> */ <add> <add>/** <add> * Contains basic common classes to handle time at nanosecond precision. <add> * <p> <add> * <h3>JSR 310 compatibility</h3> <add> * Java 8 will introduce a better time definition that is going to be very <add> * similar to these class. That effort is unfortunately too unstable to use <add> * directly. When it will be released, the plan is to phase out this package <add> * and use the standard where possible. Same definitions and conventions <add> * are taken from JSR 310 to make future conversion easier. <add> * <add> */ <add>package org.epics.util.time;
Java
apache-2.0
68675a9762afcacf45aa21ff865693b1a0cdf09e
0
MatthewTamlin/SlidingIntroScreen
/* * Copyright 2016 Matthew Tamlin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.matthewtamlin.testapp; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import com.matthewtamlin.android_utilities_library.helpers.DimensionHelper; import com.matthewtamlin.sliding_intro_screen_library.indicators.DotIndicator; import com.matthewtamlin.sliding_intro_screen_library.indicators.SelectionIndicator; import static org.hamcrest.MatcherAssert.assertThat; /** * Tests the configuration options for the page indicator. */ public class TestProgressIndicatorConfig extends ThreePageTestBase { /** * Used to identify this class during testing. */ private static final String TAG = "[TestPageIndicatorC...]"; /** * Diameter to use for the unselected dots after triggering, measured in display-independent * pixels. */ private static final int UNSELECTED_DIAMETER_DP = 3; /** * Diameter to use for the selected dot after triggering, measured in display-independent * pixels. */ private static final int SELECTED_DIAMETER_DP = 10; /** * Color to use for the unselected dots after triggering. */ private static final int UNSELECTED_COLOR = Color.RED; /** * Color to use for the selected dot after triggering. */ private static final int SELECTED_COLOR = Color.YELLOW; /** * Spacing to use between dots after triggering, measured in display-independent pixels. */ private static final int SPACING_BETWEEN_DOTS_DP = 10; /** * The duration to use when transitioning between selected and unselected, after triggering. */ private static final int TRANSITION_DURATION = 2000; /** * The number of dots to use when testing that the indicator shrinks properly. */ private static final int NUMBER_OF_ITEMS_SMALLER = 2; /** * The number of dots to use when testing that the indicator grows properly. */ private static final int NUMBER_OF_ITEMS_LARGER = 4; /** * The unselected dot diameter, converted to pixels. */ int unselectedDiameterPx; /** * The selected dot diameter, converted to pixels. */ int selectedDiameterPx; /** * The spacing between dots, converted to pixels. */ int spacingPx; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initialisePxDimensions(); LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); getRootView().addView(layout); Button showHideButton = new Button(this); layout.addView(showHideButton); showHideButton.setText("show/hide indicator"); showHideButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "[on click] [show/hide]"); SelectionIndicator progressIndicator = getProgressIndicator(); boolean initiallyHidden = progressIndicator.isVisible(); progressIndicator.setVisibility(!initiallyHidden); assertThat("progress indicator did not hide/un-hide properly", progressIndicator.isVisible() == !initiallyHidden); Log.d(TAG, "[show/hide button] [assertion passed]"); } }); Button toggleAnimations = new Button(this); layout.addView(toggleAnimations); toggleAnimations.setText("toggle animations"); toggleAnimations.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "[on click] [toggle animations]"); boolean initiallyEnabled = progressIndicatorAnimationsAreEnabled(); enableProgressIndicatorAnimations(!initiallyEnabled); assertThat("animations did not enable/disable properly", progressIndicatorAnimationsAreEnabled() == !initiallyEnabled); Log.d(TAG, "[toggle animations] [assertion passed]"); } }); Button changeIndicatorPropertiesDp = new Button(this); layout.addView(changeIndicatorPropertiesDp); changeIndicatorPropertiesDp.setText("change indicator properties (dp)"); changeIndicatorPropertiesDp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "[on click] [change indicator (dp)]"); resetIndicator(); assertThat( "tests are designed to be used with a DotIndicator and cannot run " + "otherwise", getProgressIndicator() instanceof DotIndicator); DotIndicator indicator = (DotIndicator) getProgressIndicator(); indicator.setUnselectedDotDiameterDp(UNSELECTED_DIAMETER_DP); indicator.setSelectedDotDiameterDp(SELECTED_DIAMETER_DP); indicator.setUnselectedDotColor(UNSELECTED_COLOR); indicator.setSelectedDotColor(SELECTED_COLOR); indicator.setSpacingBetweenDotsPx(spacingPx); indicator.setTransitionDuration(TRANSITION_DURATION); checkChangeAssumptions(); } }); Button changeIndicatorPropertiesPx = new Button(this); layout.addView(changeIndicatorPropertiesPx); changeIndicatorPropertiesPx.setText("change indicator properties (px)"); changeIndicatorPropertiesPx.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "[on click] [change indicator (px)]"); resetIndicator(); assertThat( "tests are designed to be used with a DotIndicator and cannot run " + "otherwise", getProgressIndicator() instanceof DotIndicator); DotIndicator indicator = (DotIndicator) getProgressIndicator(); indicator.setUnselectedDotDiameterPx(unselectedDiameterPx); indicator.setSelectedDotDiameterPx(selectedDiameterPx); indicator.setUnselectedDotColor(UNSELECTED_COLOR); indicator.setSelectedDotColor(SELECTED_COLOR); indicator.setSpacingBetweenDotsPx(spacingPx); indicator.setTransitionDuration(TRANSITION_DURATION); checkChangeAssumptions(); } }); Button shrinkIndicator = new Button(this); layout.addView(shrinkIndicator); shrinkIndicator.setText("reduce number of dots"); shrinkIndicator.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "[on click] [change number of dots]"); resetIndicator(); assertThat("tests are designed to be used with a DotIndicator and cannot run " + "otherwise", getProgressIndicator() instanceof DotIndicator); DotIndicator indicator = (DotIndicator) getProgressIndicator(); indicator.setNumberOfItems(NUMBER_OF_ITEMS_SMALLER); assertThat("incorrect number of dots shown", indicator.getNumberOfItems() == NUMBER_OF_ITEMS_SMALLER); } }); Button growIndicator = new Button(this); layout.addView(growIndicator); growIndicator.setText("increase number of dots"); growIndicator.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "[on click] [change number of dots]"); resetIndicator(); assertThat("tests are designed to be used with a DotIndicator and cannot run " + "otherwise", getProgressIndicator() instanceof DotIndicator); DotIndicator indicator = (DotIndicator) getProgressIndicator(); indicator.setNumberOfItems(NUMBER_OF_ITEMS_LARGER); assertThat("incorrect number of dots shown", indicator.getNumberOfItems() == NUMBER_OF_ITEMS_LARGER); } }); Button resetIndicatorProperties = new Button(this); layout.addView(resetIndicatorProperties); resetIndicatorProperties.setText("reset indicator properties"); resetIndicatorProperties.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "[on click] [reset indicator]"); resetIndicator(); } }); } private void initialisePxDimensions() { unselectedDiameterPx = DimensionHelper.dpToPx(UNSELECTED_DIAMETER_DP, TestProgressIndicatorConfig.this); selectedDiameterPx = DimensionHelper.dpToPx(SELECTED_DIAMETER_DP, TestProgressIndicatorConfig.this); spacingPx = DimensionHelper.dpToPx(SPACING_BETWEEN_DOTS_DP, TestProgressIndicatorConfig.this); } /** * Changes the indicator properties to a reset state. */ private void resetIndicator() { setProgressIndicator(new DotIndicator(this)); } private void checkChangeAssumptions() { DotIndicator indicator = (DotIndicator) getProgressIndicator(); indicator.setUnselectedDotDiameterPx(unselectedDiameterPx); indicator.setSelectedDotDiameterPx(selectedDiameterPx); indicator.setUnselectedDotColor(UNSELECTED_COLOR); indicator.setSelectedDotColor(SELECTED_COLOR); indicator.setSpacingBetweenDotsPx(spacingPx); indicator.setTransitionDuration(TRANSITION_DURATION); assertThat("unselected diameter was not set/returned correctly", indicator.getUnselectedDotDiameter() == unselectedDiameterPx); assertThat("selected diameter was not set/returned correctly", indicator.getSelectedDotDiameter() == selectedDiameterPx); assertThat("unselected color was not set/returned correctly", indicator.getUnselectedDotColor() == UNSELECTED_COLOR); assertThat("selected color was not set/returned correctly", indicator.getSelectedDotColor() == SELECTED_COLOR); assertThat("spacing between dots was not set/returned correctly", indicator.getSpacingBetweenDots() == spacingPx); assertThat("transition duration was not set/returned correctly", indicator.getTransitionDuration() == TRANSITION_DURATION); Log.d(TAG, "[checkChangeAssumptions] [assertions passed]"); } }
testapp/src/main/java/com/matthewtamlin/testapp/TestProgressIndicatorConfig.java
/* * Copyright 2016 Matthew Tamlin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.matthewtamlin.testapp; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import com.matthewtamlin.android_utilities_library.helpers.DimensionHelper; import com.matthewtamlin.sliding_intro_screen_library.indicators.DotIndicator; import com.matthewtamlin.sliding_intro_screen_library.indicators.SelectionIndicator; import static org.hamcrest.MatcherAssert.assertThat; /** * Tests the configuration options for the page indicator. */ public class TestProgressIndicatorConfig extends ThreePageTestBase { /** * Used to identify this class during testing. */ private static final String TAG = "[TestPageIndicatorC...]"; /** * Diameter to use for the unselected dots after triggering, measured in display-independent * pixels. */ private static final int UNSELECTED_DIAMETER_DP = 3; /** * Diameter to use for the selected dot after triggering, measured in display-independent * pixels. */ private static final int SELECTED_DIAMETER_DP = 10; /** * Color to use for the unselected dots after triggering. */ private static final int UNSELECTED_COLOR = Color.RED; /** * Color to use for the selected dot after triggering. */ private static final int SELECTED_COLOR = Color.YELLOW; /** * Spacing to use between dots after triggering, measured in display-independent pixels. */ private static final int SPACING_BETWEEN_DOTS_DP = 10; /** * The duration to use when transitioning between selected and unselected, after triggering. */ private static final int TRANSITION_DURATION = 2000; int unselectedDiameterPx; int selectedDiameterPx; int spacingPx; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initialisePxDimensions(); LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); getRootView().addView(layout); Button showHideButton = new Button(this); layout.addView(showHideButton); showHideButton.setText("show/hide indicator"); showHideButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "[on click] [show/hide]"); SelectionIndicator progressIndicator = getProgressIndicator(); boolean initiallyHidden = progressIndicator.isVisible(); progressIndicator.setVisibility(!initiallyHidden); assertThat("progress indicator did not hide/un-hide properly", progressIndicator.isVisible() == !initiallyHidden); Log.d(TAG, "[show/hide button] [assertion passed]"); } }); Button toggleAnimations = new Button(this); layout.addView(toggleAnimations); toggleAnimations.setText("toggle animations"); toggleAnimations.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "[on click] [toggle animations]"); boolean initiallyEnabled = progressIndicatorAnimationsAreEnabled(); enableProgressIndicatorAnimations(!initiallyEnabled); assertThat("animations did not enable/disable properly", progressIndicatorAnimationsAreEnabled() == !initiallyEnabled); Log.d(TAG, "[toggle animations] [assertion passed]"); } }); Button changeIndicatorPropertiesDp = new Button(this); layout.addView(changeIndicatorPropertiesDp); changeIndicatorPropertiesDp.setText("change indicator properties (dp)"); changeIndicatorPropertiesDp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "[on click] [change indicator (dp)]"); resetIndicator(); assertThat( "tests are designed to be used with a DotIndicator and cannot run " + "otherwise", getProgressIndicator() instanceof DotIndicator); DotIndicator indicator = (DotIndicator) getProgressIndicator(); indicator.setUnselectedDotDiameterDp(UNSELECTED_DIAMETER_DP); indicator.setSelectedDotDiameterDp(SELECTED_DIAMETER_DP); indicator.setUnselectedDotColor(UNSELECTED_COLOR); indicator.setSelectedDotColor(SELECTED_COLOR); indicator.setSpacingBetweenDotsPx(spacingPx); indicator.setTransitionDuration(TRANSITION_DURATION); checkChangeAssumptions(); } }); Button changeIndicatorPropertiesPx = new Button(this); layout.addView(changeIndicatorPropertiesPx); changeIndicatorPropertiesPx.setText("change indicator properties (px)"); changeIndicatorPropertiesPx.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "[on click] [change indicator (px)]"); resetIndicator(); assertThat( "tests are designed to be used with a DotIndicator and cannot run " + "otherwise", getProgressIndicator() instanceof DotIndicator); DotIndicator indicator = (DotIndicator) getProgressIndicator(); indicator.setUnselectedDotDiameterPx(unselectedDiameterPx); indicator.setSelectedDotDiameterPx(selectedDiameterPx); indicator.setUnselectedDotColor(UNSELECTED_COLOR); indicator.setSelectedDotColor(SELECTED_COLOR); indicator.setSpacingBetweenDotsPx(spacingPx); indicator.setTransitionDuration(TRANSITION_DURATION); checkChangeAssumptions(); } }); Button resetIndicatorProperties = new Button(this); layout.addView(resetIndicatorProperties); resetIndicatorProperties.setText("reset indicator properties"); resetIndicatorProperties.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "[on click] [reset indicator]"); resetIndicator(); } }); } private void initialisePxDimensions() { unselectedDiameterPx = DimensionHelper.dpToPx(UNSELECTED_DIAMETER_DP, TestProgressIndicatorConfig.this); selectedDiameterPx = DimensionHelper.dpToPx(SELECTED_DIAMETER_DP, TestProgressIndicatorConfig.this); spacingPx = DimensionHelper.dpToPx(SPACING_BETWEEN_DOTS_DP, TestProgressIndicatorConfig.this); } /** * Changes the indicator properties to a reset state. */ private void resetIndicator() { setProgressIndicator(new DotIndicator(this)); } private void checkChangeAssumptions() { DotIndicator indicator = (DotIndicator) getProgressIndicator(); indicator.setUnselectedDotDiameterPx(unselectedDiameterPx); indicator.setSelectedDotDiameterPx(selectedDiameterPx); indicator.setUnselectedDotColor(UNSELECTED_COLOR); indicator.setSelectedDotColor(SELECTED_COLOR); indicator.setSpacingBetweenDotsPx(spacingPx); indicator.setTransitionDuration(TRANSITION_DURATION); assertThat("unselected diameter was not set/returned correctly", indicator.getUnselectedDotDiameter() == unselectedDiameterPx); assertThat("selected diameter was not set/returned correctly", indicator.getSelectedDotDiameter() == selectedDiameterPx); assertThat("unselected color was not set/returned correctly", indicator.getUnselectedDotColor() == UNSELECTED_COLOR); assertThat("selected color was not set/returned correctly", indicator.getSelectedDotColor() == SELECTED_COLOR); assertThat("spacing between dots was not set/returned correctly", indicator.getSpacingBetweenDots() == spacingPx); assertThat("transition duration was not set/returned correctly", indicator.getTransitionDuration() == TRANSITION_DURATION); Log.d(TAG, "[checkChangeAssumptions] [assertions passed]"); } }
Updated TestProgressIndicatorConfig.java Widened testing coverage
testapp/src/main/java/com/matthewtamlin/testapp/TestProgressIndicatorConfig.java
Updated TestProgressIndicatorConfig.java
<ide><path>estapp/src/main/java/com/matthewtamlin/testapp/TestProgressIndicatorConfig.java <ide> */ <ide> private static final int TRANSITION_DURATION = 2000; <ide> <add> /** <add> * The number of dots to use when testing that the indicator shrinks properly. <add> */ <add> private static final int NUMBER_OF_ITEMS_SMALLER = 2; <add> <add> /** <add> * The number of dots to use when testing that the indicator grows properly. <add> */ <add> private static final int NUMBER_OF_ITEMS_LARGER = 4; <add> <add> /** <add> * The unselected dot diameter, converted to pixels. <add> */ <ide> int unselectedDiameterPx; <add> <add> /** <add> * The selected dot diameter, converted to pixels. <add> */ <ide> int selectedDiameterPx; <add> <add> /** <add> * The spacing between dots, converted to pixels. <add> */ <ide> int spacingPx; <ide> <ide> @Override <ide> indicator.setTransitionDuration(TRANSITION_DURATION); <ide> <ide> checkChangeAssumptions(); <add> } <add> }); <add> <add> Button shrinkIndicator = new Button(this); <add> layout.addView(shrinkIndicator); <add> shrinkIndicator.setText("reduce number of dots"); <add> shrinkIndicator.setOnClickListener(new View.OnClickListener() { <add> @Override <add> public void onClick(View v) { <add> Log.d(TAG, "[on click] [change number of dots]"); <add> <add> resetIndicator(); <add> <add> assertThat("tests are designed to be used with a DotIndicator and cannot run " + <add> "otherwise", getProgressIndicator() instanceof DotIndicator); <add> <add> DotIndicator indicator = (DotIndicator) getProgressIndicator(); <add> indicator.setNumberOfItems(NUMBER_OF_ITEMS_SMALLER); <add> <add> assertThat("incorrect number of dots shown", indicator.getNumberOfItems() == <add> NUMBER_OF_ITEMS_SMALLER); <add> } <add> }); <add> <add> Button growIndicator = new Button(this); <add> layout.addView(growIndicator); <add> growIndicator.setText("increase number of dots"); <add> growIndicator.setOnClickListener(new View.OnClickListener() { <add> @Override <add> public void onClick(View v) { <add> Log.d(TAG, "[on click] [change number of dots]"); <add> <add> resetIndicator(); <add> <add> assertThat("tests are designed to be used with a DotIndicator and cannot run " + <add> "otherwise", getProgressIndicator() instanceof DotIndicator); <add> <add> DotIndicator indicator = (DotIndicator) getProgressIndicator(); <add> indicator.setNumberOfItems(NUMBER_OF_ITEMS_LARGER); <add> <add> assertThat("incorrect number of dots shown", indicator.getNumberOfItems() == <add> NUMBER_OF_ITEMS_LARGER); <ide> } <ide> }); <ide>
Java
bsd-3-clause
error: pathspec 'test/net/domesdaybook/parser/regex/RegexParserTest.java' did not match any file(s) known to git
19930dbb599cfb2179a41dcd36edc28b9c45ebd0
1
uzen/byteseek
/* * Copyright Matt Palmer 2012, All rights reserved. * * This code is licensed under a standard 3-clause BSD license: * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * The names of its contributors may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package net.domesdaybook.parser.regex; import static org.junit.Assert.assertEquals; import net.domesdaybook.parser.ParseException; import net.domesdaybook.parser.tree.ParseTree; import net.domesdaybook.parser.tree.ParseTreeType; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.fail; /** * @author Matt Palmer * */ public class RegexParserTest { RegexParser parser; @Before public void setUp() { parser = new RegexParser(); } @After public void tearDown() { parser = null; } /* * Tests for null or whitespace only: */ @Test(expected=net.domesdaybook.parser.ParseException.class) public final void testNull() throws ParseException { parser.parse(null); } @Test(expected=net.domesdaybook.parser.ParseException.class) public final void testEmpty() throws ParseException { parser.parse(""); } @Test(expected=net.domesdaybook.parser.ParseException.class) public final void testTab() throws ParseException { parser.parse("\t"); } @Test(expected=net.domesdaybook.parser.ParseException.class) public final void testTabs() throws ParseException { parser.parse("\t\t\t"); } @Test(expected=net.domesdaybook.parser.ParseException.class) public final void testNewLine() throws ParseException { parser.parse("\n"); } @Test(expected=net.domesdaybook.parser.ParseException.class) public final void testNewLines() throws ParseException { parser.parse("\n\n"); } @Test(expected=net.domesdaybook.parser.ParseException.class) public final void testSpace() throws ParseException { parser.parse(" "); } @Test(expected=net.domesdaybook.parser.ParseException.class) public final void testSpaces() throws ParseException { parser.parse(" "); } @Test(expected=net.domesdaybook.parser.ParseException.class) public final void testSpacesNewLine() throws ParseException { parser.parse(" \n"); } @Test(expected=net.domesdaybook.parser.ParseException.class) public final void testWhitespaceLines() throws ParseException { parser.parse(" \n\t\r \t \n \t \n "); } /* * Tests for comments. */ @Test(expected=net.domesdaybook.parser.ParseException.class) public final void testCommentNoEndingNewLine() throws ParseException { parser.parse("#Just a comment"); } @Test(expected=net.domesdaybook.parser.ParseException.class) public final void testCommentNewLine() throws ParseException { parser.parse("#Just a comment\n"); } @Test(expected=net.domesdaybook.parser.ParseException.class) public final void testCommentsNewLines() throws ParseException { parser.parse("\n #Just a comment \n\r #Another comment\n"); } @Test(expected=net.domesdaybook.parser.ParseException.class) public final void testCommentsNoEndingNewLine() throws ParseException { parser.parse("\n #Just a comment \n\r \t #Another comment"); } /* * Tests for ParseTreeType.BYTE */ @Test public final void testByte() throws ParseException { testByte("01", (byte) 0x01); testByte(" 01 ", (byte) 0x01); testByte("FF", (byte) 0xFF); testByte("\tFF", (byte) 0xFF); testByte("00", (byte) 0x00); testByte("\n\r00", (byte) 0x00); testByte("cd", (byte) 0xcd); testByte("cd\t \n", (byte) 0xcd); testByte("d4", (byte) 0xD4); testByte(" \t d4\t ", (byte) 0xd4); testByte("fe", (byte) 0xfe); testByte("fe \r\t\n", (byte) 0xFE); testByte("7e", (byte) 0x7e); testByte("7e", (byte) 0x7e); testBad("0"); testBad(" 1"); testBad("\t\ta"); testBad("1g"); testBad(" xy\t"); } private void testByte(String expression, byte value) throws ParseException { ParseTree node = parser.parse(expression); assertEquals("Expression" + expression + " has type BYTE", ParseTreeType.BYTE, node.getParseTreeType()); assertEquals("Expression" + expression + " has value" + value, value, node.getByteValue()); assertEquals("Expression" + expression + " has no children", 0, node.getChildren().size()); } /* * Tests for ParseTreeType.ALL_BITMASK */ @Test public final void testAllBitmask() throws ParseException { testAllBitmask("&01", (byte) 0x01); testAllBitmask(" &01 ", (byte) 0x01); testAllBitmask("&FF", (byte) 0xFF); testAllBitmask("\t&ff", (byte) 0xff); testAllBitmask("&00", (byte) 0x00); testAllBitmask("\n\r &00", (byte) 0x00); testAllBitmask("&cd", (byte) 0xcd); testAllBitmask("\n\r\n\r&cD\t ", (byte) 0xCd); testAllBitmask("&d4", (byte) 0xD4); testAllBitmask(" &D4\t", (byte) 0xd4); testAllBitmask("&fe", (byte) 0xfe); testAllBitmask(" \t\t \t&fE\r", (byte) 0xfE); } private void testAllBitmask(String expression, byte value) throws ParseException { ParseTree node = parser.parse(expression); assertEquals("Expression " + expression + " type is ParseTreeType.ALL_BITMASK", ParseTreeType.ALL_BITMASK, node.getParseTreeType()); assertEquals("Expression " + expression + " value is: " + value, value, node.getByteValue()); } /* * Tests for ParseTreeType.ANY_BITMASK */ @Test public final void testAnyBitmask() throws ParseException { testAnyBitmask("~01", (byte) 0x01); testAnyBitmask("~FF", (byte) 0xFF); testAnyBitmask("~00", (byte) 0x00); testAnyBitmask("~cd", (byte) 0xcd); testAnyBitmask("~d4", (byte) 0xD4); testAnyBitmask("~fe", (byte) 0xfe); } private void testAnyBitmask(String expression, byte value) throws ParseException { ParseTree node = parser.parse(expression); assertEquals("Expression " + expression + " type is ParseTreeType.ANY_BITMASK", ParseTreeType.ANY_BITMASK, node.getParseTreeType()); assertEquals("Expression " + expression + " value is: " + value, value, node.getByteValue()); } /* * Tests for ParseTreeType.STRING */ @Test public final void testString() throws ParseException { testString("''"); testString("' '"); testString("'X'"); testString("'0'"); testString("'one two three four'"); testString("'some words\nwith a new line'"); } private void testString(String expression) throws ParseException { ParseTree node = parser.parse(expression); assertEquals("Expression " + expression + " type is ParseTreeType.STRING", ParseTreeType.STRING, node.getParseTreeType()); assertEquals("Expression " + expression + " value is: " + stripQuotes(expression), stripQuotes(expression), node.getTextValue()); assertEquals("Expression " + expression + " has no children", 0, node.getChildren().size()); } private String stripQuotes(String fromString) { return fromString.substring(1, fromString.length() - 1); } /* * Tests for ParseTreeType.CASE_INSENSITIVE_STRING */ @Test public final void testCaseInsensitiveString() throws ParseException { testCaseInsensitiveString("``"); testCaseInsensitiveString("` `"); testCaseInsensitiveString("`q`"); testCaseInsensitiveString("`7`"); testCaseInsensitiveString("`one two three four`"); testCaseInsensitiveString("`some words\nwith a new line`"); } private void testCaseInsensitiveString(String expression) throws ParseException { ParseTree node = parser.parse(expression); assertEquals("Expression " + expression + " has type ParseTreeType.CASE_INSENSITIVE_STRING", ParseTreeType.CASE_INSENSITIVE_STRING, node.getParseTreeType()); assertEquals("Expression " + expression + " has value: " + stripQuotes(expression), stripQuotes(expression), node.getTextValue()); assertEquals("Expression " + expression + " has no children", 0, node.getChildren().size()); } /* * Tests for ParseTreeType.ANY */ /* * Tests for ParseTreeType.SET */ /* * Tests for ParseTreeType.SEQUENCE */ private void testBad(String expression) { try { parser.parse(expression); fail("Expression " + expression + " was expected to generate a ParseException"); } catch (ParseException expected) {} } }
test/net/domesdaybook/parser/regex/RegexParserTest.java
Beginning of tests for regex parser.
test/net/domesdaybook/parser/regex/RegexParserTest.java
Beginning of tests for regex parser.
<ide><path>est/net/domesdaybook/parser/regex/RegexParserTest.java <add>/* <add> * Copyright Matt Palmer 2012, All rights reserved. <add> * <add> * This code is licensed under a standard 3-clause BSD license: <add> * <add> * Redistribution and use in source and binary forms, with or without modification, <add> * are permitted provided that the following conditions are met: <add> * <add> * * Redistributions of source code must retain the above copyright notice, <add> * this list of conditions and the following disclaimer. <add> * <add> * * Redistributions in binary form must reproduce the above copyright notice, <add> * this list of conditions and the following disclaimer in the documentation <add> * and/or other materials provided with the distribution. <add> * <add> * * The names of its contributors may not be used to endorse or promote products <add> * derived from this software without specific prior written permission. <add> * <add> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" <add> * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE <add> * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE <add> * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE <add> * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR <add> * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF <add> * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS <add> * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN <add> * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) <add> * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE <add> * POSSIBILITY OF SUCH DAMAGE. <add> */ <add> <add>package net.domesdaybook.parser.regex; <add> <add>import static org.junit.Assert.assertEquals; <add>import net.domesdaybook.parser.ParseException; <add>import net.domesdaybook.parser.tree.ParseTree; <add>import net.domesdaybook.parser.tree.ParseTreeType; <add> <add>import org.junit.After; <add>import org.junit.Before; <add>import org.junit.Test; <add>import static org.junit.Assert.fail; <add> <add> <add>/** <add> * @author Matt Palmer <add> * <add> */ <add>public class RegexParserTest { <add> <add> RegexParser parser; <add> <add> @Before <add> public void setUp() { <add> parser = new RegexParser(); <add> } <add> <add> @After <add> public void tearDown() { <add> parser = null; <add> } <add> <add> /* <add> * Tests for null or whitespace only: <add> */ <add> <add> @Test(expected=net.domesdaybook.parser.ParseException.class) <add> public final void testNull() throws ParseException { <add> parser.parse(null); <add> } <add> <add> @Test(expected=net.domesdaybook.parser.ParseException.class) <add> public final void testEmpty() throws ParseException { <add> parser.parse(""); <add> } <add> <add> @Test(expected=net.domesdaybook.parser.ParseException.class) <add> public final void testTab() throws ParseException { <add> parser.parse("\t"); <add> } <add> <add> @Test(expected=net.domesdaybook.parser.ParseException.class) <add> public final void testTabs() throws ParseException { <add> parser.parse("\t\t\t"); <add> } <add> <add> @Test(expected=net.domesdaybook.parser.ParseException.class) <add> public final void testNewLine() throws ParseException { <add> parser.parse("\n"); <add> } <add> <add> @Test(expected=net.domesdaybook.parser.ParseException.class) <add> public final void testNewLines() throws ParseException { <add> parser.parse("\n\n"); <add> } <add> <add> @Test(expected=net.domesdaybook.parser.ParseException.class) <add> public final void testSpace() throws ParseException { <add> parser.parse(" "); <add> } <add> <add> @Test(expected=net.domesdaybook.parser.ParseException.class) <add> public final void testSpaces() throws ParseException { <add> parser.parse(" "); <add> } <add> <add> @Test(expected=net.domesdaybook.parser.ParseException.class) <add> public final void testSpacesNewLine() throws ParseException { <add> parser.parse(" \n"); <add> } <add> <add> @Test(expected=net.domesdaybook.parser.ParseException.class) <add> public final void testWhitespaceLines() throws ParseException { <add> parser.parse(" \n\t\r \t \n \t \n "); <add> } <add> <add> /* <add> * Tests for comments. <add> */ <add> <add> @Test(expected=net.domesdaybook.parser.ParseException.class) <add> public final void testCommentNoEndingNewLine() throws ParseException { <add> parser.parse("#Just a comment"); <add> } <add> <add> @Test(expected=net.domesdaybook.parser.ParseException.class) <add> public final void testCommentNewLine() throws ParseException { <add> parser.parse("#Just a comment\n"); <add> } <add> <add> @Test(expected=net.domesdaybook.parser.ParseException.class) <add> public final void testCommentsNewLines() throws ParseException { <add> parser.parse("\n #Just a comment \n\r #Another comment\n"); <add> } <add> <add> @Test(expected=net.domesdaybook.parser.ParseException.class) <add> public final void testCommentsNoEndingNewLine() throws ParseException { <add> parser.parse("\n #Just a comment \n\r \t #Another comment"); <add> } <add> <add> /* <add> * Tests for ParseTreeType.BYTE <add> */ <add> <add> @Test <add> public final void testByte() throws ParseException { <add> testByte("01", (byte) 0x01); <add> testByte(" 01 ", (byte) 0x01); <add> testByte("FF", (byte) 0xFF); <add> testByte("\tFF", (byte) 0xFF); <add> testByte("00", (byte) 0x00); <add> testByte("\n\r00", (byte) 0x00); <add> testByte("cd", (byte) 0xcd); <add> testByte("cd\t \n", (byte) 0xcd); <add> testByte("d4", (byte) 0xD4); <add> testByte(" \t d4\t ", (byte) 0xd4); <add> testByte("fe", (byte) 0xfe); <add> testByte("fe \r\t\n", (byte) 0xFE); <add> testByte("7e", (byte) 0x7e); <add> testByte("7e", (byte) 0x7e); <add> <add> testBad("0"); <add> testBad(" 1"); <add> testBad("\t\ta"); <add> testBad("1g"); <add> testBad(" xy\t"); <add> } <add> <add> private void testByte(String expression, byte value) throws ParseException { <add> ParseTree node = parser.parse(expression); <add> assertEquals("Expression" + expression + " has type BYTE", ParseTreeType.BYTE, node.getParseTreeType()); <add> assertEquals("Expression" + expression + " has value" + value, value, node.getByteValue()); <add> assertEquals("Expression" + expression + " has no children", 0, node.getChildren().size()); <add> } <add> <add> /* <add> * Tests for ParseTreeType.ALL_BITMASK <add> */ <add> <add> @Test <add> public final void testAllBitmask() throws ParseException { <add> testAllBitmask("&01", (byte) 0x01); <add> testAllBitmask(" &01 ", (byte) 0x01); <add> testAllBitmask("&FF", (byte) 0xFF); <add> testAllBitmask("\t&ff", (byte) 0xff); <add> testAllBitmask("&00", (byte) 0x00); <add> testAllBitmask("\n\r &00", (byte) 0x00); <add> testAllBitmask("&cd", (byte) 0xcd); <add> testAllBitmask("\n\r\n\r&cD\t ", (byte) 0xCd); <add> testAllBitmask("&d4", (byte) 0xD4); <add> testAllBitmask(" &D4\t", (byte) 0xd4); <add> testAllBitmask("&fe", (byte) 0xfe); <add> testAllBitmask(" \t\t \t&fE\r", (byte) 0xfE); <add> } <add> <add> private void testAllBitmask(String expression, byte value) throws ParseException { <add> ParseTree node = parser.parse(expression); <add> assertEquals("Expression " + expression + " type is ParseTreeType.ALL_BITMASK", ParseTreeType.ALL_BITMASK, node.getParseTreeType()); <add> assertEquals("Expression " + expression + " value is: " + value, value, node.getByteValue()); <add> } <add> <add> <add> /* <add> * Tests for ParseTreeType.ANY_BITMASK <add> */ <add> <add> @Test <add> public final void testAnyBitmask() throws ParseException { <add> testAnyBitmask("~01", (byte) 0x01); <add> testAnyBitmask("~FF", (byte) 0xFF); <add> testAnyBitmask("~00", (byte) 0x00); <add> testAnyBitmask("~cd", (byte) 0xcd); <add> testAnyBitmask("~d4", (byte) 0xD4); <add> testAnyBitmask("~fe", (byte) 0xfe); <add> } <add> <add> private void testAnyBitmask(String expression, byte value) throws ParseException { <add> ParseTree node = parser.parse(expression); <add> assertEquals("Expression " + expression + " type is ParseTreeType.ANY_BITMASK", ParseTreeType.ANY_BITMASK, node.getParseTreeType()); <add> assertEquals("Expression " + expression + " value is: " + value, value, node.getByteValue()); <add> } <add> <add> /* <add> * Tests for ParseTreeType.STRING <add> */ <add> <add> @Test <add> public final void testString() throws ParseException { <add> testString("''"); <add> testString("' '"); <add> testString("'X'"); <add> testString("'0'"); <add> testString("'one two three four'"); <add> testString("'some words\nwith a new line'"); <add> } <add> <add> private void testString(String expression) throws ParseException { <add> ParseTree node = parser.parse(expression); <add> assertEquals("Expression " + expression + " type is ParseTreeType.STRING", ParseTreeType.STRING, node.getParseTreeType()); <add> assertEquals("Expression " + expression + " value is: " + stripQuotes(expression), stripQuotes(expression), node.getTextValue()); <add> assertEquals("Expression " + expression + " has no children", 0, node.getChildren().size()); <add> } <add> <add> private String stripQuotes(String fromString) { <add> return fromString.substring(1, fromString.length() - 1); <add> } <add> <add> /* <add> * Tests for ParseTreeType.CASE_INSENSITIVE_STRING <add> */ <add> <add> @Test <add> public final void testCaseInsensitiveString() throws ParseException { <add> testCaseInsensitiveString("``"); <add> testCaseInsensitiveString("` `"); <add> testCaseInsensitiveString("`q`"); <add> testCaseInsensitiveString("`7`"); <add> testCaseInsensitiveString("`one two three four`"); <add> testCaseInsensitiveString("`some words\nwith a new line`"); <add> } <add> <add> private void testCaseInsensitiveString(String expression) throws ParseException { <add> ParseTree node = parser.parse(expression); <add> assertEquals("Expression " + expression + " has type ParseTreeType.CASE_INSENSITIVE_STRING", ParseTreeType.CASE_INSENSITIVE_STRING, node.getParseTreeType()); <add> assertEquals("Expression " + expression + " has value: " + stripQuotes(expression), stripQuotes(expression), node.getTextValue()); <add> assertEquals("Expression " + expression + " has no children", 0, node.getChildren().size()); <add> } <add> <add> /* <add> * Tests for ParseTreeType.ANY <add> */ <add> <add> <add> <add> /* <add> * Tests for ParseTreeType.SET <add> */ <add> <add> <add> <add> /* <add> * Tests for ParseTreeType.SEQUENCE <add> */ <add> <add> <add> private void testBad(String expression) { <add> try { <add> parser.parse(expression); <add> fail("Expression " + expression + " was expected to generate a ParseException"); <add> } catch (ParseException expected) {} <add> } <add> <add> <add> <add>}
JavaScript
mit
29570c663d91ae1d91c90cb5600e9f46815f3694
0
alex-georgiou/fractional-arithmetic
/*fractional-arithmetic 1.2.1 139d75d "2017-01-12 21:51:17 +0200" */ function NotAFractionError(a){this.name="NotAFractionError",this.message=a||"Not a Fraction"}function Fraction(a,b){if("undefined"==typeof a)throw new NotAFractionError("You must specify a fraction");if(!(this instanceof Fraction))return new Fraction(a,b);if(a instanceof Fraction&&"undefined"==typeof b)return this.n=a.n,void(this.d=a.d);if(isInteger(a)&&isInteger(b))return this.n=parseInt(a),void(this.d=parseInt(b));if(isInteger(a)&&"undefined"==typeof b)return this.n=parseInt(a),void(this.d=1);if("number"==typeof a){var c=""+a,d=c.length-c.indexOf(".")-1;return this.n=parseInt(c.replace(".","")),void(this.d=Math.pow(10,d))}throw new NotAFractionError("Cannot instantiate Fraction("+a+("undefined"==typeof b?"":b)+")")}var isInteger=function(a){return!isNaN(a)&&parseInt(a)==parseFloat(a)};module.exports.isInteger=isInteger;var gcd=function(a,b){a=Math.abs(a),b=Math.abs(b);for(var c;b>0;)c=b,b=a%b,a=c;return a};module.exports.gcd=gcd;var lcm=function(a,b){return a=Math.abs(a),b=Math.abs(b),a*(b/gcd(a,b))};module.exports.lcm=lcm,NotAFractionError.prototype=new Error,NotAFractionError.prototype.constructor=NotAFractionError,Fraction.prototype.toString=Fraction.prototype.toS=Fraction.prototype.inspect=function(){return"("+this.n+"/"+this.d+")"},Fraction.prototype.toNumber=function(){return this.n/this.d},Fraction.prototype.toLatex=function(){return"\\frac{"+this.n+"}{"+this.d+"}"},Fraction.prototype.toMathML=function(){return"<mfrac><mn>"+this.n+"</mn><mn>"+this.d+"</mfrac>"},Fraction.prototype.simplify=function(){this.d<0&&(this.n*=-1,this.d*=-1);var a=gcd(this.n,this.d);return 1==a?this:new Fraction(this.n/a,this.d/a)},Fraction.prototype.inverse=function(){return new Fraction(this.d,this.n)},Fraction.prototype.times=Fraction.prototype.multiply=function(a,b){if(a instanceof Fraction&&"undefined"==typeof b)return new Fraction(this.n*a.n,this.d*a.d).simplify();if(isInteger(a)&&isInteger(b))return this.times(new Fraction(a,b));throw new NotAFractionError("Cannot multiply "+this+" with n="+a+", d="+b)},Fraction.prototype.dividedBy=Fraction.prototype.div=function(a,b){if(a instanceof Fraction&&"undefined"==typeof b)return a.inverse().times(this);if(isInteger(a)&&isInteger(b))return this.times(new Fraction(b,a));throw new NotAFractionError("Cannot divide "+this+" by n="+a+", d="+b)},Fraction.prototype.plus=function(a,b){if(a instanceof Fraction&&"undefined"==typeof b){var c=lcm(this.d,a.d);return new Fraction(this.n*c/this.d+a.n*c/a.d,c)}if(isInteger(a)&&isInteger(b))return this.plus(new Fraction(a,b));throw new NotAFractionError("Cannot add "+this+" to n="+a+", d="+b)},Fraction.prototype.minus=function(a,b){if(a instanceof Fraction&&"undefined"==typeof b){var c=lcm(this.d,a.d);return new Fraction(this.n*c/this.d-a.n*c/a.d,c)}if(isInteger(a)&&isInteger(b))return this.minus(new Fraction(a,b));throw new NotAFractionError("Cannot add "+this+" to n="+a+", d="+b)},module.exports.Fraction=Fraction;
fractional-arithmetic.min.js
/*fractional-arithmetic 1.2.1 93deba5 "2017-01-12 21:51:17 +0200" */ function NotAFractionError(a){this.name="NotAFractionError",this.message=a||"Not a Fraction"}function Fraction(a,b){if("undefined"==typeof a)throw new NotAFractionError("You must specify a fraction");if(!(this instanceof Fraction))return new Fraction(a,b);if(a instanceof Fraction&&"undefined"==typeof b)return this.n=a.n,void(this.d=a.d);if(isInteger(a)&&isInteger(b))return this.n=parseInt(a),void(this.d=parseInt(b));if(isInteger(a)&&"undefined"==typeof b)return this.n=parseInt(a),void(this.d=1);if("number"==typeof a){var c=""+a,d=c.length-c.indexOf(".")-1;return this.n=parseInt(c.replace(".","")),void(this.d=Math.pow(10,d))}throw new NotAFractionError("Cannot instantiate Fraction("+a+("undefined"==typeof b?"":b)+")")}var isInteger=function(a){return!isNaN(a)&&parseInt(a)==parseFloat(a)};module.exports.isInteger=isInteger;var gcd=function(a,b){a=Math.abs(a),b=Math.abs(b);for(var c;b>0;)c=b,b=a%b,a=c;return a};module.exports.gcd=gcd;var lcm=function(a,b){return a=Math.abs(a),b=Math.abs(b),a*(b/gcd(a,b))};module.exports.lcm=lcm,NotAFractionError.prototype=new Error,NotAFractionError.prototype.constructor=NotAFractionError,Fraction.prototype.toString=Fraction.prototype.toS=Fraction.prototype.inspect=function(){return"("+this.n+"/"+this.d+")"},Fraction.prototype.toNumber=function(){return this.n/this.d},Fraction.prototype.toLatex=function(){return"\\frac{"+this.n+"}{"+this.d+"}"},Fraction.prototype.toMathML=function(){return"<mfrac><mn>"+this.n+"</mn><mn>"+this.d+"</mfrac>"},Fraction.prototype.simplify=function(){this.d<0&&(this.n*=-1,this.d*=-1);var a=gcd(this.n,this.d);return 1==a?this:new Fraction(this.n/a,this.d/a)},Fraction.prototype.inverse=function(){return new Fraction(this.d,this.n)},Fraction.prototype.times=Fraction.prototype.multiply=function(a,b){if(a instanceof Fraction&&"undefined"==typeof b)return new Fraction(this.n*a.n,this.d*a.d).simplify();if(isInteger(a)&&isInteger(b))return this.times(new Fraction(a,b));throw new NotAFractionError("Cannot multiply "+this+" with n="+a+", d="+b)},Fraction.prototype.dividedBy=Fraction.prototype.div=function(a,b){if(a instanceof Fraction&&"undefined"==typeof b)return a.inverse().times(this);if(isInteger(a)&&isInteger(b))return this.times(new Fraction(b,a));throw new NotAFractionError("Cannot divide "+this+" by n="+a+", d="+b)},Fraction.prototype.plus=function(a,b){if(a instanceof Fraction&&"undefined"==typeof b){var c=lcm(this.d,a.d);return new Fraction(this.n*c/this.d+a.n*c/a.d,c)}if(isInteger(a)&&isInteger(b))return this.plus(new Fraction(a,b));throw new NotAFractionError("Cannot add "+this+" to n="+a+", d="+b)},Fraction.prototype.minus=function(a,b){if(a instanceof Fraction&&"undefined"==typeof b){var c=lcm(this.d,a.d);return new Fraction(this.n*c/this.d-a.n*c/a.d,c)}if(isInteger(a)&&isInteger(b))return this.minus(new Fraction(a,b));throw new NotAFractionError("Cannot add "+this+" to n="+a+", d="+b)},module.exports.Fraction=Fraction;
adding minified code
fractional-arithmetic.min.js
adding minified code
<ide><path>ractional-arithmetic.min.js <del>/*fractional-arithmetic 1.2.1 93deba5 "2017-01-12 21:51:17 +0200" */ <add>/*fractional-arithmetic 1.2.1 139d75d "2017-01-12 21:51:17 +0200" */ <ide> function NotAFractionError(a){this.name="NotAFractionError",this.message=a||"Not a Fraction"}function Fraction(a,b){if("undefined"==typeof a)throw new NotAFractionError("You must specify a fraction");if(!(this instanceof Fraction))return new Fraction(a,b);if(a instanceof Fraction&&"undefined"==typeof b)return this.n=a.n,void(this.d=a.d);if(isInteger(a)&&isInteger(b))return this.n=parseInt(a),void(this.d=parseInt(b));if(isInteger(a)&&"undefined"==typeof b)return this.n=parseInt(a),void(this.d=1);if("number"==typeof a){var c=""+a,d=c.length-c.indexOf(".")-1;return this.n=parseInt(c.replace(".","")),void(this.d=Math.pow(10,d))}throw new NotAFractionError("Cannot instantiate Fraction("+a+("undefined"==typeof b?"":b)+")")}var isInteger=function(a){return!isNaN(a)&&parseInt(a)==parseFloat(a)};module.exports.isInteger=isInteger;var gcd=function(a,b){a=Math.abs(a),b=Math.abs(b);for(var c;b>0;)c=b,b=a%b,a=c;return a};module.exports.gcd=gcd;var lcm=function(a,b){return a=Math.abs(a),b=Math.abs(b),a*(b/gcd(a,b))};module.exports.lcm=lcm,NotAFractionError.prototype=new Error,NotAFractionError.prototype.constructor=NotAFractionError,Fraction.prototype.toString=Fraction.prototype.toS=Fraction.prototype.inspect=function(){return"("+this.n+"/"+this.d+")"},Fraction.prototype.toNumber=function(){return this.n/this.d},Fraction.prototype.toLatex=function(){return"\\frac{"+this.n+"}{"+this.d+"}"},Fraction.prototype.toMathML=function(){return"<mfrac><mn>"+this.n+"</mn><mn>"+this.d+"</mfrac>"},Fraction.prototype.simplify=function(){this.d<0&&(this.n*=-1,this.d*=-1);var a=gcd(this.n,this.d);return 1==a?this:new Fraction(this.n/a,this.d/a)},Fraction.prototype.inverse=function(){return new Fraction(this.d,this.n)},Fraction.prototype.times=Fraction.prototype.multiply=function(a,b){if(a instanceof Fraction&&"undefined"==typeof b)return new Fraction(this.n*a.n,this.d*a.d).simplify();if(isInteger(a)&&isInteger(b))return this.times(new Fraction(a,b));throw new NotAFractionError("Cannot multiply "+this+" with n="+a+", d="+b)},Fraction.prototype.dividedBy=Fraction.prototype.div=function(a,b){if(a instanceof Fraction&&"undefined"==typeof b)return a.inverse().times(this);if(isInteger(a)&&isInteger(b))return this.times(new Fraction(b,a));throw new NotAFractionError("Cannot divide "+this+" by n="+a+", d="+b)},Fraction.prototype.plus=function(a,b){if(a instanceof Fraction&&"undefined"==typeof b){var c=lcm(this.d,a.d);return new Fraction(this.n*c/this.d+a.n*c/a.d,c)}if(isInteger(a)&&isInteger(b))return this.plus(new Fraction(a,b));throw new NotAFractionError("Cannot add "+this+" to n="+a+", d="+b)},Fraction.prototype.minus=function(a,b){if(a instanceof Fraction&&"undefined"==typeof b){var c=lcm(this.d,a.d);return new Fraction(this.n*c/this.d-a.n*c/a.d,c)}if(isInteger(a)&&isInteger(b))return this.minus(new Fraction(a,b));throw new NotAFractionError("Cannot add "+this+" to n="+a+", d="+b)},module.exports.Fraction=Fraction;
Java
apache-2.0
ce976683ac50a9dec95ec00c8532d5477ca4ccc2
0
neopixl/Spitfire
package com.neopixl.library.spitfire; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.android.volley.DefaultRetryPolicy; import com.android.volley.RetryPolicy; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; /** * Main class used to store the object mapper <b>ObjectMapper</b> and the default retry policy <b>RetryPolicy</b> used by all requests. It acts as a singleton. * <p>Created by Florian ALONSO on 12/30/16. * For Neopixl</p> */ public final class SpitfireManager { @Nullable private static ObjectMapper objectMapper; @NonNull private static RetryPolicy defaultRetryPolicy = generateRetryPolicy(); private static int requestTimeout = 30000;// 30 seconds /** * Sets the timeout * @param timeout default timeout for all requests */ public static void setRequestTimeout(int timeout) { requestTimeout = timeout; defaultRetryPolicy = generateRetryPolicy(); } /** * Store a retry policy * @param newRetryPolicy <b>RetryPolicy</b>, not null */ public static void setDefaultRetryPolicy(@NonNull RetryPolicy newRetryPolicy) { defaultRetryPolicy = newRetryPolicy; } /** * Get the default retry policy * @return the default retry policy <b>RetryPolicy</b>, not null */ @NonNull public static RetryPolicy getDefaultRetryPolicy() { return defaultRetryPolicy; } /** * Get the default object mapper (with SerializationFeature.INDENT_OUTPUT set to false and SerializationInclusion set to JsonInclude.Include.NON_NULL) * @return the current object mapper <b>ObjectMapper</b>, not null */ @NonNull public static ObjectMapper getObjectMapper() { if (objectMapper == null) { objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } return objectMapper; } /** * Generate a default retry policy (30 seconds for the timeout, 1 retry maximum, 1 backoff multiplier) * @return a default retry policy, not null */ @NonNull private static RetryPolicy generateRetryPolicy() { return new DefaultRetryPolicy(requestTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); } }
spitfire/src/main/java/com/neopixl/library/spitfire/SpitfireManager.java
package com.neopixl.library.spitfire; import android.support.annotation.NonNull; import com.android.volley.DefaultRetryPolicy; import com.android.volley.RetryPolicy; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; /** * Main class used to store the object mapper <b>ObjectMapper</b> and the default retry policy <b>RetryPolicy</b> used by all requests. It acts as a singleton. * <p>Created by Florian ALONSO on 12/30/16. * For Neopixl</p> */ public final class SpitfireManager { private static ObjectMapper objectMapper; @NonNull private static RetryPolicy defaultRetryPolicy = generateRetryPolicy(); private static int requestTimeout = 30000;// 30 seconds /** * Sets the timeout * @param timeout default timeout for all requests */ public static void setRequestTimeout(int timeout) { requestTimeout = timeout; defaultRetryPolicy = generateRetryPolicy(); } /** * Store a retry policy * @param newRetryPolicy <b>RetryPolicy</b>, not null */ public static void setDefaultRetryPolicy(@NonNull RetryPolicy newRetryPolicy) { defaultRetryPolicy = newRetryPolicy; } /** * Get the default retry policy * @return the default retry policy <b>RetryPolicy</b>, not null */ public static RetryPolicy getDefaultRetryPolicy() { return defaultRetryPolicy; } /** * Get the default object mapper (with SerializationFeature.INDENT_OUTPUT set to false and SerializationInclusion set to JsonInclude.Include.NON_NULL) * @return the current object mapper <b>ObjectMapper</b>, not null */ @NonNull public static ObjectMapper getObjectMapper() { if (objectMapper == null) { objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } return objectMapper; } /** * Generate a default retry policy (30 seconds for the timeout, 1 retry maximum, 1 backoff multiplier) * @return a default retry policy, not null */ @NonNull private static RetryPolicy generateRetryPolicy() { return new DefaultRetryPolicy(requestTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); } }
Added some annotations
spitfire/src/main/java/com/neopixl/library/spitfire/SpitfireManager.java
Added some annotations
<ide><path>pitfire/src/main/java/com/neopixl/library/spitfire/SpitfireManager.java <ide> package com.neopixl.library.spitfire; <ide> <ide> import android.support.annotation.NonNull; <add>import android.support.annotation.Nullable; <ide> <ide> import com.android.volley.DefaultRetryPolicy; <ide> import com.android.volley.RetryPolicy; <ide> <ide> public final class SpitfireManager { <ide> <add> @Nullable <ide> private static ObjectMapper objectMapper; <ide> <ide> @NonNull <ide> * Get the default retry policy <ide> * @return the default retry policy <b>RetryPolicy</b>, not null <ide> */ <add> @NonNull <ide> public static RetryPolicy getDefaultRetryPolicy() { <ide> return defaultRetryPolicy; <ide> }
JavaScript
mit
82b191992f468e323427b9d6595ceae136845d8f
0
haadcode/orbit,shamb0t/orbit,shamb0t/orbit,shamb0t/orbit,haadcode/anonymous-networks,haadcode/anonymous-networks,haadcode/orbit,haadcode/anonymous-networks,haadcode/orbit
'use strict' if(process.env.ENV === 'dev') delete process.versions['electron'] const electron = require('electron') const app = electron.app const BrowserWindow = electron.BrowserWindow const Menu = electron.Menu const ipcMain = electron.ipcMain const dialog = electron.dialog const fs = require('fs') const path = require('path') const Logger = require('logplease') const IpfsDaemon = require('ipfs-daemon') // dev|debug const MODE = process.env.ENV ? process.env.ENV : 'debug' // TODO: move directory setup to its own file // Get data directories const userHomeDir = app.getPath("home") const userDownloadDir = app.getPath("downloads") const appDataDir = app.getPath("userData") const ipfsDataDir = process.env.IPFS_PATH ? path.resolve(process.env.IPFS_PATH) : path.join(appDataDir, '/ipfs') const orbitDataDir = (MODE === 'dev') ? path.join(process.cwd() , '/data') // put orbit's data to './data' in dev mode : path.join(appDataDir, '/orbit-data') // Make sure we have the Orbit data directory if (!fs.existsSync(appDataDir)) fs.mkdirSync(appDataDir) if (!fs.existsSync(orbitDataDir)) fs.mkdirSync(orbitDataDir) // Set IPFS daemon's paths and addresses, and CORS const daemonSettings = { AppDataDir: orbitDataDir, IpfsDataDir: ipfsDataDir, Addresses: { API: '/ip4/127.0.0.1/tcp/0', Swarm: ['/ip4/0.0.0.0/tcp/0'], Gateway: '/ip4/0.0.0.0/tcp/0' }, API: { HTTPHeaders: { "Access-Control-Allow-Origin": ['*'], "Access-Control-Allow-Methods": ["PUT", "GET", "POST"], "Access-Control-Allow-Credentials": ["true"] } } } // Setup logging const logger = Logger.create("Orbit.Index-Native") Logger.setLogfile(path.join(orbitDataDir, '/debug.log')) Logger.setLogLevel('DEBUG') // Default window settings const connectWindowSize = { width: 512, height: 512, center: true, resize: false, "web-preferences": { "web-security": false, zoomFactor: 3.0 } } const mainWindowSize = { width: 1200, height: 800, } // Menu bar const template = require('./menu-native')(app) const menu = Menu.buildFromTemplate(template) // Handle shutdown gracefully const shutdown = () => { logger.info("Shutting down...") setTimeout(() => { logger.info("All done!") app.quit() process.exit(0) }, 1000) } app.on('window-all-closed', shutdown) process.on('SIGINT', () => shutdown) process.on('SIGTERM', () => shutdown) // Log errors process.on('uncaughtException', (error) => { // Skip 'ctrl-c' error and shutdown gracefully const match = String(error).match(/non-zero exit code 255/) if(match) shutdown() else logger.error(error) }) // Window handling let mainWindow const setWindowToNormal = () => { mainWindow.setSize(mainWindowSize.width, mainWindowSize.height) mainWindow.setResizable(true) mainWindow.center() } const setWindowToLogin = () => { mainWindow.setSize(connectWindowSize.width, connectWindowSize.height) mainWindow.setResizable(false) mainWindow.center() } // Start logger.debug("Run index.js in '" + MODE + "' mode") app.on('ready', () => { try { mainWindow = new BrowserWindow(connectWindowSize) mainWindow.webContents.session.setDownloadPath(path.resolve(userDownloadDir)) Menu.setApplicationMenu(menu) // Pass the mode and electron flag to the html (renderer process) global.DEV = MODE === 'dev' global.isElectron = true global.ipfsDaemonSettings = daemonSettings // Resize the window as per app state ipcMain.on('connected', (event) => setWindowToNormal()) ipcMain.on('disconnected', (event) => setWindowToLogin()) // Load the dist build or connect to webpack-dev-server const indexUrl = MODE === 'dev' ? 'http://localhost:8000/' : 'file://' + __dirname + '/client/dist/index.html' mainWindow.loadURL(indexUrl) // Bind the Orbit IPFS daemon to a random port, set CORS // IpfsDaemon(daemonSettings) // .then((res) => { // // We have a running IPFS daemon // const ipfsDaemon = res.daemon // const gatewayAddr = res.Addresses.Gateway // // // Pass the ipfs (api) instance and gateway address to the renderer process // global.ipfsInstance = res.ipfs // global.gatewayAddress = gatewayAddr ? gatewayAddr : 'localhost:8080/ipfs/' // // // If the window is closed, assume we quit // mainWindow.on('closed', () => { // mainWindow = null // ipfsDaemon.stopDaemon() // }) // // }) // .catch((err) => { // logger.error(err) // dialog.showMessageBox({ // type: 'error', // buttons: ['Ok'], // title: 'Error', // message: err.message, // detail: err.stack // }, () => process.exit(1)) // }) } catch(e) { logger.error("Error in index-native:", e) } })
index.js
'use strict' if(process.env.ENV === 'dev') delete process.versions['electron'] const electron = require('electron') const app = electron.app const BrowserWindow = electron.BrowserWindow const Menu = electron.Menu const ipcMain = electron.ipcMain const dialog = electron.dialog const fs = require('fs') const path = require('path') const Logger = require('logplease') const IpfsDaemon = require('ipfs-daemon') // dev|debug const MODE = process.env.ENV ? process.env.ENV : 'debug' // TODO: move directory setup to its own file // Get data directories const userHomeDir = app.getPath("home") const userDownloadDir = app.getPath("downloads") const appDataDir = app.getPath("userData") const ipfsDataDir = process.env.IPFS_PATH ? path.resolve(process.env.IPFS_PATH) : path.join(appDataDir, '/ipfs') const orbitDataDir = (MODE === 'dev') ? path.join(process.cwd() , '/data') // put orbit's data to './data' in dev mode : path.join(appDataDir, '/orbit-data') // Make sure we have the Orbit data directory if (!fs.existsSync(appDataDir)) fs.mkdirSync(appDataDir) if (!fs.existsSync(orbitDataDir)) fs.mkdirSync(orbitDataDir) // Set IPFS daemon's paths and addresses, and CORS const daemonSettings = { AppDataDir: orbitDataDir, IpfsDataDir: ipfsDataDir, Addresses: { API: '/ip4/127.0.0.1/tcp/0', Swarm: ['/ip4/0.0.0.0/tcp/0'], Gateway: '/ip4/0.0.0.0/tcp/0' }, API: { HTTPHeaders: { "Access-Control-Allow-Origin": ['*'], "Access-Control-Allow-Methods": ["PUT", "GET", "POST"], "Access-Control-Allow-Credentials": ["true"] } } } // Setup logging const logger = Logger.create("Orbit.Index-Native") Logger.setLogfile(path.join(orbitDataDir, '/debug.log')) Logger.setLogLevel('DEBUG') // Default window settings const connectWindowSize = { width: 512, height: 512, center: true, resize: false, "web-preferences": { "web-security": false, zoomFactor: 3.0 } } const mainWindowSize = { width: 1200, height: 800, } // Menu bar const template = require('./menu-native')(app) const menu = Menu.buildFromTemplate(template) // Handle shutdown gracefully const shutdown = () => { logger.info("Shutting down...") setTimeout(() => { logger.info("All done!") app.quit() process.exit(0) }, 1000) } app.on('window-all-closed', shutdown) process.on('SIGINT', () => shutdown) process.on('SIGTERM', () => shutdown) // Log errors process.on('uncaughtException', (error) => { // Skip 'ctrl-c' error and shutdown gracefully const match = String(error).match(/non-zero exit code 255/) if(match) shutdown() else logger.error(error) }) // Window handling let mainWindow const setWindowToNormal = () => { mainWindow.setSize(mainWindowSize.width, mainWindowSize.height) mainWindow.setResizable(true) mainWindow.center() } const setWindowToLogin = () => { mainWindow.setSize(connectWindowSize.width, connectWindowSize.height) mainWindow.setResizable(false) mainWindow.center() } // Start logger.debug("Run index.js in '" + MODE + "' mode") app.on('ready', () => { try { mainWindow = new BrowserWindow(connectWindowSize) mainWindow.webContents.session.setDownloadPath(path.resolve(userDownloadDir)) Menu.setApplicationMenu(menu) // Pass the mode and electron flag to the html (renderer process) global.DEV = MODE === 'dev' global.isElectron = true // Resize the window as per app state ipcMain.on('connected', (event) => setWindowToNormal()) ipcMain.on('disconnected', (event) => setWindowToLogin()) // Load and display a loading screen while we boot up mainWindow.loadURL('file://' + __dirname + '/client/dist/loading.html') // Bind the Orbit IPFS daemon to a random port, set CORS IpfsDaemon(daemonSettings) .then((res) => { // We have a running IPFS daemon const ipfsDaemon = res.daemon const gatewayAddr = res.Addresses.Gateway // Pass the ipfs (api) instance and gateway address to the renderer process global.ipfsInstance = res.ipfs global.gatewayAddress = gatewayAddr ? gatewayAddr : 'localhost:8080/ipfs/' // If the window is closed, assume we quit mainWindow.on('closed', () => { mainWindow = null ipfsDaemon.stopDaemon() }) // Load the dist build or connect to webpack-dev-server const indexUrl = MODE === 'dev' ? 'http://localhost:8000/' : 'file://' + __dirname + '/client/dist/index.html' mainWindow.loadURL(indexUrl) }) .catch((err) => { logger.error(err) dialog.showMessageBox({ type: 'error', buttons: ['Ok'], title: 'Error', message: err.message, detail: err.stack }, () => process.exit(1)) }) } catch(e) { logger.error("Error in index-native:", e) } })
removing ipfs daemon start in index.ks
index.js
removing ipfs daemon start in index.ks
<ide><path>ndex.js <ide> "Access-Control-Allow-Origin": ['*'], <ide> "Access-Control-Allow-Methods": ["PUT", "GET", "POST"], <ide> "Access-Control-Allow-Credentials": ["true"] <del> } <add> } <ide> } <ide> } <ide> <ide> // Pass the mode and electron flag to the html (renderer process) <ide> global.DEV = MODE === 'dev' <ide> global.isElectron = true <del> <add> global.ipfsDaemonSettings = daemonSettings <ide> // Resize the window as per app state <ide> ipcMain.on('connected', (event) => setWindowToNormal()) <ide> ipcMain.on('disconnected', (event) => setWindowToLogin()) <ide> <del> // Load and display a loading screen while we boot up <del> mainWindow.loadURL('file://' + __dirname + '/client/dist/loading.html') <add> // Load the dist build or connect to webpack-dev-server <add> const indexUrl = MODE === 'dev' <add> ? 'http://localhost:8000/' <add> : 'file://' + __dirname + '/client/dist/index.html' <add> <add> mainWindow.loadURL(indexUrl) <ide> <ide> // Bind the Orbit IPFS daemon to a random port, set CORS <del> IpfsDaemon(daemonSettings) <del> .then((res) => { <del> // We have a running IPFS daemon <del> const ipfsDaemon = res.daemon <del> const gatewayAddr = res.Addresses.Gateway <del> <del> // Pass the ipfs (api) instance and gateway address to the renderer process <del> global.ipfsInstance = res.ipfs <del> global.gatewayAddress = gatewayAddr ? gatewayAddr : 'localhost:8080/ipfs/' <del> <del> // If the window is closed, assume we quit <del> mainWindow.on('closed', () => { <del> mainWindow = null <del> ipfsDaemon.stopDaemon() <del> }) <del> <del> // Load the dist build or connect to webpack-dev-server <del> const indexUrl = MODE === 'dev' <del> ? 'http://localhost:8000/' <del> : 'file://' + __dirname + '/client/dist/index.html' <del> <del> mainWindow.loadURL(indexUrl) <del> }) <del> .catch((err) => { <del> logger.error(err) <del> dialog.showMessageBox({ <del> type: 'error', <del> buttons: ['Ok'], <del> title: 'Error', <del> message: err.message, <del> detail: err.stack <del> }, () => process.exit(1)) <del> }) <add> // IpfsDaemon(daemonSettings) <add> // .then((res) => { <add> // // We have a running IPFS daemon <add> // const ipfsDaemon = res.daemon <add> // const gatewayAddr = res.Addresses.Gateway <add> // <add> // // Pass the ipfs (api) instance and gateway address to the renderer process <add> // global.ipfsInstance = res.ipfs <add> // global.gatewayAddress = gatewayAddr ? gatewayAddr : 'localhost:8080/ipfs/' <add> // <add> // // If the window is closed, assume we quit <add> // mainWindow.on('closed', () => { <add> // mainWindow = null <add> // ipfsDaemon.stopDaemon() <add> // }) <add> // <add> // }) <add> // .catch((err) => { <add> // logger.error(err) <add> // dialog.showMessageBox({ <add> // type: 'error', <add> // buttons: ['Ok'], <add> // title: 'Error', <add> // message: err.message, <add> // detail: err.stack <add> // }, () => process.exit(1)) <add> // }) <ide> } catch(e) { <ide> logger.error("Error in index-native:", e) <ide> }
Java
apache-2.0
641aaac91bae44b3791d420e13313bdafb12565f
0
smartnews/presto,Praveen2112/presto,smartnews/presto,dain/presto,losipiuk/presto,Praveen2112/presto,ebyhr/presto,ebyhr/presto,dain/presto,Praveen2112/presto,dain/presto,ebyhr/presto,smartnews/presto,losipiuk/presto,losipiuk/presto,Praveen2112/presto,ebyhr/presto,losipiuk/presto,smartnews/presto,losipiuk/presto,smartnews/presto,dain/presto,ebyhr/presto,Praveen2112/presto,dain/presto
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.memory; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.primitives.Ints; import io.trino.Session; import io.trino.execution.QueryStats; import io.trino.metadata.QualifiedObjectName; import io.trino.operator.OperatorStats; import io.trino.plugin.base.metrics.LongCount; import io.trino.spi.QueryId; import io.trino.spi.metrics.Count; import io.trino.spi.metrics.Metric; import io.trino.spi.metrics.Metrics; import io.trino.sql.analyzer.FeaturesConfig; import io.trino.testing.AbstractTestQueryFramework; import io.trino.testing.DistributedQueryRunner; import io.trino.testing.MaterializedResult; import io.trino.testing.MaterializedRow; import io.trino.testing.QueryRunner; import io.trino.testing.ResultWithQueryId; import io.trino.testng.services.Flaky; import org.intellij.lang.annotations.Language; import org.testng.annotations.Test; import java.util.List; import java.util.Map; import static com.google.common.collect.ImmutableList.toImmutableList; import static io.trino.SystemSessionProperties.ENABLE_LARGE_DYNAMIC_FILTERS; import static io.trino.SystemSessionProperties.JOIN_DISTRIBUTION_TYPE; import static io.trino.SystemSessionProperties.JOIN_REORDERING_STRATEGY; import static io.trino.plugin.memory.MemoryQueryRunner.createMemoryQueryRunner; import static io.trino.sql.analyzer.FeaturesConfig.JoinDistributionType.BROADCAST; import static io.trino.sql.analyzer.FeaturesConfig.JoinDistributionType.PARTITIONED; import static io.trino.sql.analyzer.FeaturesConfig.JoinReorderingStrategy.NONE; import static io.trino.testing.assertions.Assert.assertEquals; import static io.trino.tpch.TpchTable.CUSTOMER; import static io.trino.tpch.TpchTable.LINE_ITEM; import static io.trino.tpch.TpchTable.NATION; import static io.trino.tpch.TpchTable.ORDERS; import static io.trino.tpch.TpchTable.PART; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertTrue; @Test(singleThreaded = true) public class TestMemorySmoke extends AbstractTestQueryFramework { private static final int LINEITEM_COUNT = 60175; private static final int ORDERS_COUNT = 15000; private static final int PART_COUNT = 2000; private static final int CUSTOMER_COUNT = 1500; @Override protected QueryRunner createQueryRunner() throws Exception { return createMemoryQueryRunner( // Adjust DF limits to test edge cases ImmutableMap.of( "dynamic-filtering.small-broadcast.max-distinct-values-per-driver", "100", "dynamic-filtering.small-broadcast.range-row-limit-per-driver", "100", "dynamic-filtering.large-broadcast.max-distinct-values-per-driver", "100", "dynamic-filtering.large-broadcast.range-row-limit-per-driver", "100000", // disable semi join to inner join rewrite to test semi join operators explicitly "optimizer.rewrite-filtering-semi-join-to-inner-join", "false"), ImmutableList.of(NATION, CUSTOMER, ORDERS, LINE_ITEM, PART)); } @Test public void testCreateAndDropTable() { int tablesBeforeCreate = listMemoryTables().size(); assertUpdate("CREATE TABLE test AS SELECT * FROM tpch.tiny.nation", "SELECT count(*) FROM nation"); assertEquals(listMemoryTables().size(), tablesBeforeCreate + 1); assertUpdate("DROP TABLE test"); assertEquals(listMemoryTables().size(), tablesBeforeCreate); } // it has to be RuntimeException as FailureInfo$FailureException is private @Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "line 1:1: Destination table 'memory.default.nation' already exists") public void testCreateTableWhenTableIsAlreadyCreated() { @Language("SQL") String createTableSql = "CREATE TABLE nation AS SELECT * FROM tpch.tiny.nation"; assertUpdate(createTableSql); } @Test public void testSelect() { assertUpdate("CREATE TABLE test_select AS SELECT * FROM tpch.tiny.nation", "SELECT count(*) FROM nation"); assertQuery("SELECT * FROM test_select ORDER BY nationkey", "SELECT * FROM nation ORDER BY nationkey"); assertQueryResult("INSERT INTO test_select SELECT * FROM tpch.tiny.nation", 25L); assertQueryResult("INSERT INTO test_select SELECT * FROM tpch.tiny.nation", 25L); assertQueryResult("SELECT count(*) FROM test_select", 75L); } @Test public void testCustomMetricsScanFilter() { Map<String, Metric> metrics = collectCustomMetrics("SELECT partkey FROM part WHERE partkey % 1000 > 0"); assertThat(metrics.get("rows")).isEqualTo(new LongCount(PART_COUNT)); assertThat(metrics.get("started")).isEqualTo(metrics.get("finished")); assertThat(((Count) metrics.get("finished")).getTotal()).isGreaterThan(0); } @Test public void testCustomMetricsScanOnly() { Map<String, Metric> metrics = collectCustomMetrics("SELECT partkey FROM part"); assertThat(metrics.get("rows")).isEqualTo(new LongCount(PART_COUNT)); assertThat(metrics.get("started")).isEqualTo(metrics.get("finished")); assertThat(((Count) metrics.get("finished")).getTotal()).isGreaterThan(0); } private Map<String, Metric> collectCustomMetrics(String sql) { DistributedQueryRunner runner = (DistributedQueryRunner) getQueryRunner(); ResultWithQueryId<MaterializedResult> result = runner.executeWithQueryId(getSession(), sql); return runner .getCoordinator() .getQueryManager() .getFullQueryInfo(result.getQueryId()) .getQueryStats() .getOperatorSummaries() .stream() .map(OperatorStats::getMetrics) .reduce(Metrics.EMPTY, Metrics::mergeWith) .getMetrics(); } @Test public void testJoinDynamicFilteringNone() { // Probe-side is not scanned at all, due to dynamic filtering: assertDynamicFiltering( "SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND orders.totalprice < 0", withBroadcastJoin(), 0, 0, ORDERS_COUNT); } @Test public void testJoinLargeBuildSideDynamicFiltering() { @Language("SQL") String sql = "SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey and orders.custkey BETWEEN 300 AND 700"; int expectedRowCount = 15793; // Probe-side is fully scanned because the build-side is too large for dynamic filtering: assertDynamicFiltering( sql, withBroadcastJoin(), expectedRowCount, LINEITEM_COUNT, ORDERS_COUNT); // Probe-side is partially scanned because we extract min/max from large build-side for dynamic filtering assertDynamicFiltering( sql, withLargeDynamicFilters(), expectedRowCount, 60139, ORDERS_COUNT); } @Test public void testPartitionedJoinNoDynamicFiltering() { // Probe-side is fully scanned, because local dynamic filtering does not work for partitioned joins: assertDynamicFiltering( "SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND orders.totalprice < 0", withPartitionedJoin(), 0, LINEITEM_COUNT, ORDERS_COUNT); } @Test public void testJoinDynamicFilteringSingleValue() { assertQueryResult("SELECT orderkey FROM orders WHERE comment = 'nstructions sleep furiously among '", 1L); assertQueryResult("SELECT COUNT() FROM lineitem WHERE orderkey = 1", 6L); assertQueryResult("SELECT partkey FROM part WHERE comment = 'onic deposits'", 1552L); assertQueryResult("SELECT COUNT() FROM lineitem WHERE partkey = 1552", 39L); // Join lineitem with a single row of orders assertDynamicFiltering( "SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND orders.comment = 'nstructions sleep furiously among '", withBroadcastJoin(), 6, 6, ORDERS_COUNT); // Join lineitem with a single row of part assertDynamicFiltering( "SELECT l.comment FROM lineitem l, part p WHERE p.partkey = l.partkey AND p.comment = 'onic deposits'", withBroadcastJoin(), 39, 39, PART_COUNT); } @Test public void testJoinDynamicFilteringImplicitCoercion() { assertUpdate("CREATE TABLE coerce_test AS SELECT CAST(orderkey as INT) orderkey_int FROM tpch.tiny.lineitem", "SELECT count(*) FROM lineitem"); // Probe-side is partially scanned, dynamic filters from build side are coerced to the probe column type assertDynamicFiltering( "SELECT * FROM coerce_test l JOIN orders o ON l.orderkey_int = o.orderkey AND o.comment = 'nstructions sleep furiously among '", withBroadcastJoin(), 6, 6, ORDERS_COUNT); } @Test public void testJoinDynamicFilteringBlockProbeSide() { // Wait for both build sides to finish before starting the scan of 'lineitem' table (should be very selective given the dynamic filters). assertDynamicFiltering( "SELECT l.comment" + " FROM lineitem l, part p, orders o" + " WHERE l.orderkey = o.orderkey AND o.comment = 'nstructions sleep furiously among '" + " AND p.partkey = l.partkey AND p.comment = 'onic deposits'", withBroadcastJoinNonReordering(), 1, 1, PART_COUNT, ORDERS_COUNT); } @Test public void testSemiJoinDynamicFilteringNone() { // Probe-side is not scanned at all, due to dynamic filtering: assertDynamicFiltering( "SELECT * FROM lineitem WHERE lineitem.orderkey IN (SELECT orders.orderkey FROM orders WHERE orders.totalprice < 0)", withBroadcastJoin(), 0, 0, ORDERS_COUNT); } @Test public void testSemiJoinLargeBuildSideDynamicFiltering() { // Probe-side is fully scanned because the build-side is too large for dynamic filtering: @Language("SQL") String sql = "SELECT * FROM lineitem WHERE lineitem.orderkey IN " + "(SELECT orders.orderkey FROM orders WHERE orders.custkey BETWEEN 300 AND 700)"; int expectedRowCount = 15793; // Probe-side is fully scanned because the build-side is too large for dynamic filtering: assertDynamicFiltering( sql, withBroadcastJoin(), expectedRowCount, LINEITEM_COUNT, ORDERS_COUNT); // Probe-side is partially scanned because we extract min/max from large build-side for dynamic filtering assertDynamicFiltering( sql, withLargeDynamicFilters(), expectedRowCount, 60139, ORDERS_COUNT); } @Test public void testPartitionedSemiJoinNoDynamicFiltering() { // Probe-side is fully scanned, because local dynamic filtering does not work for partitioned joins: assertDynamicFiltering( "SELECT * FROM lineitem WHERE lineitem.orderkey IN (SELECT orders.orderkey FROM orders WHERE orders.totalprice < 0)", withPartitionedJoin(), 0, LINEITEM_COUNT, ORDERS_COUNT); } @Test public void testSemiJoinDynamicFilteringSingleValue() { // Join lineitem with a single row of orders assertDynamicFiltering( "SELECT * FROM lineitem WHERE lineitem.orderkey IN (SELECT orders.orderkey FROM orders WHERE orders.comment = 'nstructions sleep furiously among ')", withBroadcastJoin(), 6, 6, ORDERS_COUNT); // Join lineitem with a single row of part assertDynamicFiltering( "SELECT l.comment FROM lineitem l WHERE l.partkey IN (SELECT p.partkey FROM part p WHERE p.comment = 'onic deposits')", withBroadcastJoin(), 39, 39, PART_COUNT); } @Test public void testSemiJoinDynamicFilteringBlockProbeSide() { // Wait for both build sides to finish before starting the scan of 'lineitem' table (should be very selective given the dynamic filters). assertDynamicFiltering( "SELECT t.comment FROM " + "(SELECT * FROM lineitem l WHERE l.orderkey IN (SELECT o.orderkey FROM orders o WHERE o.comment = 'nstructions sleep furiously among ')) t " + "WHERE t.partkey IN (SELECT p.partkey FROM part p WHERE p.comment = 'onic deposits')", withBroadcastJoinNonReordering(), 1, 1, ORDERS_COUNT, PART_COUNT); } @Test @Flaky(issue = "https://github.com/trinodb/trino/issues/5172", match = "Lists differ at element") public void testCrossJoinDynamicFiltering() { assertUpdate("DROP TABLE IF EXISTS probe"); assertUpdate("CREATE TABLE probe (k VARCHAR, v INTEGER)"); assertUpdate("INSERT INTO probe VALUES ('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', NULL)", 5); assertUpdate("DROP TABLE IF EXISTS build"); assertUpdate("CREATE TABLE build (vmin INTEGER, vmax INTEGER)"); assertUpdate("INSERT INTO build VALUES (1, 2), (NULL, NULL)", 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin", withBroadcastJoin(), 3, 3, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin", withBroadcastJoin(), 2, 2, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v <= vmax", withBroadcastJoin(), 3, 3, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v < vmax", withBroadcastJoin(), 2, 2, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin AND v < vmax", withBroadcastJoin(), 1, 1, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin AND v <= vmax", withBroadcastJoin(), 1, 1, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin AND v < vmax", withBroadcastJoin(), 0, 0, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin AND vmax < 0", withBroadcastJoin(), 0, 0, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin AND vmax", withBroadcastJoin(), 2, 2, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin AND v <= vmax", withBroadcastJoin(), 2, 2, 2); assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin AND vmax", withBroadcastJoin(), 2, 2, 2); assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin AND v <= vmax", withBroadcastJoin(), 2, 2, 2); // TODO: support complex inequality join clauses: https://github.com/trinodb/trino/issues/5755 assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin AND vmax - 1", withBroadcastJoin(), 1, 3, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin + 1 AND vmax", withBroadcastJoin(), 1, 3, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin + 1 AND vmax - 1", withBroadcastJoin(), 0, 5, 2); assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin AND vmax - 1", withBroadcastJoin(), 1, 3, 2); assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin + 1 AND vmax", withBroadcastJoin(), 1, 3, 2); assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin + 1 AND vmax - 1", withBroadcastJoin(), 0, 5, 2); // TODO: make sure it works after https://github.com/trinodb/trino/issues/5777 is fixed assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin AND v <= vmax - 1", withBroadcastJoin(), 1, 1, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin + 1 AND v <= vmax", withBroadcastJoin(), 1, 1, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin + 1 AND v <= vmax - 1", withBroadcastJoin(), 0, 0, 2); // TODO: support complex inequality join clauses: https://github.com/trinodb/trino/issues/5755 assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin AND v <= vmax - 1", withBroadcastJoin(), 1, 3, 2); assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin + 1 AND v <= vmax", withBroadcastJoin(), 1, 3, 2); assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin + 1 AND v <= vmax - 1", withBroadcastJoin(), 0, 5, 2); assertDynamicFiltering("SELECT * FROM probe WHERE v <= (SELECT max(vmax) FROM build)", withBroadcastJoin(), 3, 3, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v IS NOT DISTINCT FROM vmin", withBroadcastJoin(), 2, 2, 2); } @Test public void testIsNotDistinctFromNaN() { assertUpdate("DROP TABLE IF EXISTS probe_nan"); assertUpdate("CREATE TABLE probe_nan (v DOUBLE)"); assertUpdate("INSERT INTO probe_nan VALUES 0, 1, 2, NULL, nan()", 5); assertUpdate("DROP TABLE IF EXISTS build_nan"); assertUpdate("CREATE TABLE build_nan (v DOUBLE)"); assertUpdate("INSERT INTO build_nan VALUES 1, NULL, nan()", 3); assertDynamicFiltering("SELECT * FROM probe_nan p JOIN build_nan b ON p.v IS NOT DISTINCT FROM b.v", withBroadcastJoin(), 3, 5, 3); assertDynamicFiltering("SELECT * FROM probe_nan p JOIN build_nan b ON p.v = b.v", withBroadcastJoin(), 1, 1, 3); } @Test public void testCrossJoinLargeBuildSideDynamicFiltering() { // Probe-side is fully scanned because the build-side is too large for dynamic filtering: assertDynamicFiltering( "SELECT * FROM orders o, customer c WHERE o.custkey < c.custkey AND c.name < 'Customer#000001000' AND o.custkey > 1000", withBroadcastJoin(), 0, ORDERS_COUNT, CUSTOMER_COUNT); } @Test public void testJoinDynamicFilteringMultiJoin() { assertUpdate("CREATE TABLE t0 (k0 integer, v0 real)"); assertUpdate("CREATE TABLE t1 (k1 integer, v1 real)"); assertUpdate("CREATE TABLE t2 (k2 integer, v2 real)"); assertUpdate("INSERT INTO t0 VALUES (1, 1.0)", 1); assertUpdate("INSERT INTO t1 VALUES (1, 2.0)", 1); assertUpdate("INSERT INTO t2 VALUES (1, 3.0)", 1); String query = "SELECT k0, k1, k2 FROM t0, t1, t2 WHERE (k0 = k1) AND (k0 = k2) AND (v0 + v1 = v2)"; Session session = Session.builder(getSession()) .setSystemProperty(JOIN_DISTRIBUTION_TYPE, FeaturesConfig.JoinDistributionType.BROADCAST.name()) .setSystemProperty(JOIN_REORDERING_STRATEGY, FeaturesConfig.JoinReorderingStrategy.NONE.name()) .build(); assertQuery(session, query, "SELECT 1, 1, 1"); } private void assertDynamicFiltering(@Language("SQL") String selectQuery, Session session, int expectedRowCount, int... expectedOperatorRowsRead) { ResultWithQueryId<MaterializedResult> result = getDistributedQueryRunner().executeWithQueryId(session, selectQuery); assertEquals(result.getResult().getRowCount(), expectedRowCount); assertEquals(getOperatorRowsRead(getDistributedQueryRunner(), result.getQueryId()), Ints.asList(expectedOperatorRowsRead)); } private Session withBroadcastJoin() { return Session.builder(getSession()) .setSystemProperty(JOIN_DISTRIBUTION_TYPE, BROADCAST.name()) .build(); } private Session withLargeDynamicFilters() { return Session.builder(getSession()) .setSystemProperty(JOIN_DISTRIBUTION_TYPE, BROADCAST.name()) .setSystemProperty(ENABLE_LARGE_DYNAMIC_FILTERS, "true") .build(); } private Session withBroadcastJoinNonReordering() { return Session.builder(getSession()) .setSystemProperty(JOIN_DISTRIBUTION_TYPE, BROADCAST.name()) .setSystemProperty(JOIN_REORDERING_STRATEGY, NONE.name()) .build(); } private Session withPartitionedJoin() { return Session.builder(getSession()) .setSystemProperty(JOIN_DISTRIBUTION_TYPE, PARTITIONED.name()) .build(); } private static List<Integer> getOperatorRowsRead(DistributedQueryRunner runner, QueryId queryId) { QueryStats stats = runner.getCoordinator().getQueryManager().getFullQueryInfo(queryId).getQueryStats(); return stats.getOperatorSummaries() .stream() .filter(summary -> summary.getOperatorType().contains("Scan")) .map(OperatorStats::getInputPositions) .map(Math::toIntExact) .collect(toImmutableList()); } @Test public void testCreateTableWithNoData() { assertUpdate("CREATE TABLE test_empty (a BIGINT)"); assertQueryResult("SELECT count(*) FROM test_empty", 0L); assertQueryResult("INSERT INTO test_empty SELECT nationkey FROM tpch.tiny.nation", 25L); assertQueryResult("SELECT count(*) FROM test_empty", 25L); } @Test public void testCreateFilteredOutTable() { assertUpdate("CREATE TABLE filtered_out AS SELECT nationkey FROM tpch.tiny.nation WHERE nationkey < 0", "SELECT count(nationkey) FROM nation WHERE nationkey < 0"); assertQueryResult("SELECT count(*) FROM filtered_out", 0L); assertQueryResult("INSERT INTO filtered_out SELECT nationkey FROM tpch.tiny.nation", 25L); assertQueryResult("SELECT count(*) FROM filtered_out", 25L); } @Test public void testSelectFromEmptyTable() { assertUpdate("CREATE TABLE test_select_empty AS SELECT * FROM tpch.tiny.nation WHERE nationkey > 1000", "SELECT count(*) FROM nation WHERE nationkey > 1000"); assertQueryResult("SELECT count(*) FROM test_select_empty", 0L); } @Test public void testSelectSingleRow() { assertQuery("SELECT * FROM tpch.tiny.nation WHERE nationkey = 1", "SELECT * FROM nation WHERE nationkey = 1"); } @Test public void testSelectColumnsSubset() { assertQuery("SELECT nationkey, regionkey FROM tpch.tiny.nation ORDER BY nationkey", "SELECT nationkey, regionkey FROM nation ORDER BY nationkey"); } @Test public void testCreateSchema() { assertQueryFails("DROP SCHEMA schema1", "line 1:1: Schema 'memory.schema1' does not exist"); assertUpdate("CREATE SCHEMA schema1"); assertQueryFails("CREATE SCHEMA schema1", "line 1:1: Schema 'memory.schema1' already exists"); assertUpdate("CREATE TABLE schema1.x(t int)"); assertQueryFails("DROP SCHEMA schema1", "Schema not empty: schema1"); assertUpdate("DROP TABLE schema1.x"); assertUpdate("DROP SCHEMA schema1"); assertQueryFails("DROP SCHEMA schema1", "line 1:1: Schema 'memory.schema1' does not exist"); assertUpdate("DROP SCHEMA IF EXISTS schema1"); } @Test public void testCreateTableInNonDefaultSchema() { assertUpdate("CREATE SCHEMA schema1"); assertUpdate("CREATE SCHEMA schema2"); assertQueryResult("SHOW SCHEMAS", "default", "information_schema", "schema1", "schema2"); assertUpdate("CREATE TABLE schema1.nation AS SELECT * FROM tpch.tiny.nation WHERE nationkey % 2 = 0", "SELECT count(*) FROM nation WHERE MOD(nationkey, 2) = 0"); assertUpdate("CREATE TABLE schema2.nation AS SELECT * FROM tpch.tiny.nation WHERE nationkey % 2 = 1", "SELECT count(*) FROM nation WHERE MOD(nationkey, 2) = 1"); assertQueryResult("SELECT count(*) FROM schema1.nation", 13L); assertQueryResult("SELECT count(*) FROM schema2.nation", 12L); } @Test public void testCreateTableAndViewInNotExistSchema() { int tablesBeforeCreate = listMemoryTables().size(); assertQueryFails("CREATE TABLE schema3.test_table3 (x date)", "Schema schema3 not found"); assertQueryFails("CREATE VIEW schema4.test_view4 AS SELECT 123 x", "Schema schema4 not found"); assertQueryFails("CREATE OR REPLACE VIEW schema5.test_view5 AS SELECT 123 x", "Schema schema5 not found"); int tablesAfterCreate = listMemoryTables().size(); assertEquals(tablesBeforeCreate, tablesAfterCreate); } @Test public void testRenameTable() { assertUpdate("CREATE TABLE test_table_to_be_renamed (a BIGINT)"); assertQueryFails("ALTER TABLE test_table_to_be_renamed RENAME TO memory.test_schema_not_exist.test_table_renamed", "Schema test_schema_not_exist not found"); assertUpdate("ALTER TABLE test_table_to_be_renamed RENAME TO test_table_renamed"); assertQueryResult("SELECT count(*) FROM test_table_renamed", 0L); assertUpdate("CREATE SCHEMA test_different_schema"); assertUpdate("ALTER TABLE test_table_renamed RENAME TO test_different_schema.test_table_renamed"); assertQueryResult("SELECT count(*) FROM test_different_schema.test_table_renamed", 0L); assertUpdate("DROP TABLE test_different_schema.test_table_renamed"); assertUpdate("DROP SCHEMA test_different_schema"); } @Test public void testViews() { @Language("SQL") String query = "SELECT orderkey, orderstatus, totalprice / 2 half FROM orders"; assertUpdate("CREATE VIEW test_view AS SELECT 123 x"); assertUpdate("CREATE OR REPLACE VIEW test_view AS " + query); assertQueryFails("CREATE TABLE test_view (x date)", "View \\[default.test_view] already exists"); assertQueryFails("CREATE VIEW test_view AS SELECT 123 x", "View already exists: default.test_view"); assertQuery("SELECT * FROM test_view", query); assertTrue(computeActual("SHOW TABLES").getOnlyColumnAsSet().contains("test_view")); assertUpdate("DROP VIEW test_view"); assertQueryFails("DROP VIEW test_view", "line 1:1: View 'memory.default.test_view' does not exist"); } @Test public void testRenameView() { @Language("SQL") String query = "SELECT orderkey, orderstatus, totalprice / 2 half FROM orders"; assertUpdate("CREATE VIEW test_view_to_be_renamed AS " + query); assertQueryFails("ALTER VIEW test_view_to_be_renamed RENAME TO memory.test_schema_not_exist.test_view_renamed", "Schema test_schema_not_exist not found"); assertUpdate("ALTER VIEW test_view_to_be_renamed RENAME TO test_view_renamed"); assertQuery("SELECT * FROM test_view_renamed", query); assertUpdate("CREATE SCHEMA test_different_schema"); assertUpdate("ALTER VIEW test_view_renamed RENAME TO test_different_schema.test_view_renamed"); assertQuery("SELECT * FROM test_different_schema.test_view_renamed", query); assertUpdate("DROP VIEW test_different_schema.test_view_renamed"); assertUpdate("DROP SCHEMA test_different_schema"); } private List<QualifiedObjectName> listMemoryTables() { return getQueryRunner().listTables(getSession(), "memory", "default"); } private void assertQueryResult(@Language("SQL") String sql, Object... expected) { MaterializedResult rows = computeActual(sql); assertEquals(rows.getRowCount(), expected.length); for (int i = 0; i < expected.length; i++) { MaterializedRow materializedRow = rows.getMaterializedRows().get(i); int fieldCount = materializedRow.getFieldCount(); assertEquals(fieldCount, 1, format("Expected only one column, but got '%d'", fieldCount)); Object value = materializedRow.getField(0); assertEquals(value, expected[i]); assertEquals(materializedRow.getFieldCount(), 1); } } }
plugin/trino-memory/src/test/java/io/trino/plugin/memory/TestMemorySmoke.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.memory; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.primitives.Ints; import io.trino.Session; import io.trino.execution.QueryStats; import io.trino.metadata.QualifiedObjectName; import io.trino.operator.OperatorStats; import io.trino.plugin.base.metrics.LongCount; import io.trino.spi.QueryId; import io.trino.spi.metrics.Count; import io.trino.spi.metrics.Metric; import io.trino.spi.metrics.Metrics; import io.trino.sql.analyzer.FeaturesConfig; import io.trino.testing.AbstractTestQueryFramework; import io.trino.testing.DistributedQueryRunner; import io.trino.testing.MaterializedResult; import io.trino.testing.MaterializedRow; import io.trino.testing.QueryRunner; import io.trino.testing.ResultWithQueryId; import io.trino.testng.services.Flaky; import org.intellij.lang.annotations.Language; import org.testng.annotations.Test; import java.util.List; import java.util.Map; import static com.google.common.collect.ImmutableList.toImmutableList; import static io.trino.SystemSessionProperties.ENABLE_LARGE_DYNAMIC_FILTERS; import static io.trino.SystemSessionProperties.JOIN_DISTRIBUTION_TYPE; import static io.trino.SystemSessionProperties.JOIN_REORDERING_STRATEGY; import static io.trino.plugin.memory.MemoryQueryRunner.createMemoryQueryRunner; import static io.trino.sql.analyzer.FeaturesConfig.JoinDistributionType.BROADCAST; import static io.trino.sql.analyzer.FeaturesConfig.JoinDistributionType.PARTITIONED; import static io.trino.sql.analyzer.FeaturesConfig.JoinReorderingStrategy.NONE; import static io.trino.testing.assertions.Assert.assertEquals; import static io.trino.tpch.TpchTable.CUSTOMER; import static io.trino.tpch.TpchTable.LINE_ITEM; import static io.trino.tpch.TpchTable.NATION; import static io.trino.tpch.TpchTable.ORDERS; import static io.trino.tpch.TpchTable.PART; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertTrue; @Test(singleThreaded = true) public class TestMemorySmoke extends AbstractTestQueryFramework { private static final int LINEITEM_COUNT = 60175; private static final int ORDERS_COUNT = 15000; private static final int PART_COUNT = 2000; private static final int CUSTOMER_COUNT = 1500; @Override protected QueryRunner createQueryRunner() throws Exception { return createMemoryQueryRunner( // Adjust DF limits to test edge cases ImmutableMap.of( "dynamic-filtering.small-broadcast.max-distinct-values-per-driver", "100", "dynamic-filtering.small-broadcast.range-row-limit-per-driver", "100", "dynamic-filtering.large-broadcast.max-distinct-values-per-driver", "100", "dynamic-filtering.large-broadcast.range-row-limit-per-driver", "100000", // disable semi join to inner join rewrite to test semi join operators explicitly "optimizer.rewrite-filtering-semi-join-to-inner-join", "false"), ImmutableList.of(NATION, CUSTOMER, ORDERS, LINE_ITEM, PART)); } @Test public void testCreateAndDropTable() { int tablesBeforeCreate = listMemoryTables().size(); assertUpdate("CREATE TABLE test AS SELECT * FROM tpch.tiny.nation", "SELECT count(*) FROM nation"); assertEquals(listMemoryTables().size(), tablesBeforeCreate + 1); assertUpdate("DROP TABLE test"); assertEquals(listMemoryTables().size(), tablesBeforeCreate); } // it has to be RuntimeException as FailureInfo$FailureException is private @Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "line 1:1: Destination table 'memory.default.nation' already exists") public void testCreateTableWhenTableIsAlreadyCreated() { @Language("SQL") String createTableSql = "CREATE TABLE nation AS SELECT * FROM tpch.tiny.nation"; assertUpdate(createTableSql); } @Test public void testSelect() { assertUpdate("CREATE TABLE test_select AS SELECT * FROM tpch.tiny.nation", "SELECT count(*) FROM nation"); assertQuery("SELECT * FROM test_select ORDER BY nationkey", "SELECT * FROM nation ORDER BY nationkey"); assertQueryResult("INSERT INTO test_select SELECT * FROM tpch.tiny.nation", 25L); assertQueryResult("INSERT INTO test_select SELECT * FROM tpch.tiny.nation", 25L); assertQueryResult("SELECT count(*) FROM test_select", 75L); } @Test public void testCustomMetricsScanFilter() { Map<String, Metric> metrics = collectCustomMetrics("SELECT partkey FROM part WHERE partkey % 1000 > 0"); assertThat(metrics.get("rows")).isEqualTo(new LongCount(PART_COUNT)); assertThat(metrics.get("started")).isEqualTo(metrics.get("finished")); assertThat(((Count) metrics.get("finished")).getTotal()).isGreaterThan(0); } @Test public void testCustomMetricsScanOnly() { Map<String, Metric> metrics = collectCustomMetrics("SELECT partkey FROM part"); assertThat(metrics.get("rows")).isEqualTo(new LongCount(PART_COUNT)); assertThat(metrics.get("started")).isEqualTo(metrics.get("finished")); assertThat(((Count) metrics.get("finished")).getTotal()).isGreaterThan(0); } private Map<String, Metric> collectCustomMetrics(String sql) { DistributedQueryRunner runner = (DistributedQueryRunner) getQueryRunner(); ResultWithQueryId<MaterializedResult> result = runner.executeWithQueryId(getSession(), sql); return runner .getCoordinator() .getQueryManager() .getFullQueryInfo(result.getQueryId()) .getQueryStats() .getOperatorSummaries() .stream() .map(OperatorStats::getMetrics) .reduce(Metrics.EMPTY, Metrics::mergeWith) .getMetrics(); } @Test public void testJoinDynamicFilteringNone() { // Probe-side is not scanned at all, due to dynamic filtering: assertDynamicFiltering( "SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND orders.totalprice < 0", withBroadcastJoin(), 0, 0, ORDERS_COUNT); } @Test public void testJoinLargeBuildSideDynamicFiltering() { @Language("SQL") String sql = "SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey and orders.custkey BETWEEN 300 AND 700"; int expectedRowCount = 15793; // Probe-side is fully scanned because the build-side is too large for dynamic filtering: assertDynamicFiltering( sql, withBroadcastJoin(), expectedRowCount, LINEITEM_COUNT, ORDERS_COUNT); // Probe-side is partially scanned because we extract min/max from large build-side for dynamic filtering assertDynamicFiltering( sql, withLargeDynamicFilters(), expectedRowCount, 60139, ORDERS_COUNT); } @Test public void testPartitionedJoinNoDynamicFiltering() { // Probe-side is fully scanned, because local dynamic filtering does not work for partitioned joins: assertDynamicFiltering( "SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND orders.totalprice < 0", withPartitionedJoin(), 0, LINEITEM_COUNT, ORDERS_COUNT); } @Test public void testJoinDynamicFilteringSingleValue() { assertQueryResult("SELECT orderkey FROM orders WHERE comment = 'nstructions sleep furiously among '", 1L); assertQueryResult("SELECT COUNT() FROM lineitem WHERE orderkey = 1", 6L); assertQueryResult("SELECT partkey FROM part WHERE comment = 'onic deposits'", 1552L); assertQueryResult("SELECT COUNT() FROM lineitem WHERE partkey = 1552", 39L); // Join lineitem with a single row of orders assertDynamicFiltering( "SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND orders.comment = 'nstructions sleep furiously among '", withBroadcastJoin(), 6, 6, ORDERS_COUNT); // Join lineitem with a single row of part assertDynamicFiltering( "SELECT l.comment FROM lineitem l, part p WHERE p.partkey = l.partkey AND p.comment = 'onic deposits'", withBroadcastJoin(), 39, 39, PART_COUNT); } @Test public void testJoinDynamicFilteringImplicitCoercion() { assertUpdate("CREATE TABLE coerce_test AS SELECT CAST(orderkey as INT) orderkey_int FROM tpch.tiny.lineitem", "SELECT count(*) FROM lineitem"); // Probe-side is partially scanned, dynamic filters from build side are coerced to the probe column type assertDynamicFiltering( "SELECT * FROM coerce_test l JOIN orders o ON l.orderkey_int = o.orderkey AND o.comment = 'nstructions sleep furiously among '", withBroadcastJoin(), 6, 6, ORDERS_COUNT); } @Test public void testJoinDynamicFilteringBlockProbeSide() { // Wait for both build sides to finish before starting the scan of 'lineitem' table (should be very selective given the dynamic filters). assertDynamicFiltering( "SELECT l.comment" + " FROM lineitem l, part p, orders o" + " WHERE l.orderkey = o.orderkey AND o.comment = 'nstructions sleep furiously among '" + " AND p.partkey = l.partkey AND p.comment = 'onic deposits'", withBroadcastJoinNonReordering(), 1, 1, PART_COUNT, ORDERS_COUNT); } @Test public void testSemiJoinDynamicFilteringNone() { // Probe-side is not scanned at all, due to dynamic filtering: assertDynamicFiltering( "SELECT * FROM lineitem WHERE lineitem.orderkey IN (SELECT orders.orderkey FROM orders WHERE orders.totalprice < 0)", withBroadcastJoin(), 0, 0, ORDERS_COUNT); } @Test public void testSemiJoinLargeBuildSideDynamicFiltering() { // Probe-side is fully scanned because the build-side is too large for dynamic filtering: @Language("SQL") String sql = "SELECT * FROM lineitem WHERE lineitem.orderkey IN " + "(SELECT orders.orderkey FROM orders WHERE orders.custkey BETWEEN 300 AND 700)"; int expectedRowCount = 15793; // Probe-side is fully scanned because the build-side is too large for dynamic filtering: assertDynamicFiltering( sql, withBroadcastJoin(), expectedRowCount, LINEITEM_COUNT, ORDERS_COUNT); // Probe-side is partially scanned because we extract min/max from large build-side for dynamic filtering assertDynamicFiltering( sql, withLargeDynamicFilters(), expectedRowCount, 60139, ORDERS_COUNT); } @Test public void testPartitionedSemiJoinNoDynamicFiltering() { // Probe-side is fully scanned, because local dynamic filtering does not work for partitioned joins: assertDynamicFiltering( "SELECT * FROM lineitem WHERE lineitem.orderkey IN (SELECT orders.orderkey FROM orders WHERE orders.totalprice < 0)", withPartitionedJoin(), 0, LINEITEM_COUNT, ORDERS_COUNT); } @Test public void testSemiJoinDynamicFilteringSingleValue() { // Join lineitem with a single row of orders assertDynamicFiltering( "SELECT * FROM lineitem WHERE lineitem.orderkey IN (SELECT orders.orderkey FROM orders WHERE orders.comment = 'nstructions sleep furiously among ')", withBroadcastJoin(), 6, 6, ORDERS_COUNT); // Join lineitem with a single row of part assertDynamicFiltering( "SELECT l.comment FROM lineitem l WHERE l.partkey IN (SELECT p.partkey FROM part p WHERE p.comment = 'onic deposits')", withBroadcastJoin(), 39, 39, PART_COUNT); } @Test public void testSemiJoinDynamicFilteringBlockProbeSide() { // Wait for both build sides to finish before starting the scan of 'lineitem' table (should be very selective given the dynamic filters). assertDynamicFiltering( "SELECT t.comment FROM " + "(SELECT * FROM lineitem l WHERE l.orderkey IN (SELECT o.orderkey FROM orders o WHERE o.comment = 'nstructions sleep furiously among ')) t " + "WHERE t.partkey IN (SELECT p.partkey FROM part p WHERE p.comment = 'onic deposits')", withBroadcastJoinNonReordering(), 1, 1, ORDERS_COUNT, PART_COUNT); } @Test @Flaky(issue = "https://github.com/trinodb/trino/issues/5172", match = "Lists differ at element") public void testCrossJoinDynamicFiltering() { assertUpdate("DROP TABLE IF EXISTS probe"); assertUpdate("CREATE TABLE probe (k VARCHAR, v INTEGER)"); assertUpdate("INSERT INTO probe VALUES ('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', NULL)", 5); assertUpdate("DROP TABLE IF EXISTS build"); assertUpdate("CREATE TABLE build (vmin INTEGER, vmax INTEGER)"); assertUpdate("INSERT INTO build VALUES (1, 2), (NULL, NULL)", 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin", withBroadcastJoin(), 3, 3, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin", withBroadcastJoin(), 2, 2, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v <= vmax", withBroadcastJoin(), 3, 3, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v < vmax", withBroadcastJoin(), 2, 2, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin AND v < vmax", withBroadcastJoin(), 1, 1, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin AND v <= vmax", withBroadcastJoin(), 1, 1, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin AND v < vmax", withBroadcastJoin(), 0, 0, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin AND vmax < 0", withBroadcastJoin(), 0, 0, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin AND vmax", withBroadcastJoin(), 2, 2, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin AND v <= vmax", withBroadcastJoin(), 2, 2, 2); assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin AND vmax", withBroadcastJoin(), 2, 2, 2); assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin AND v <= vmax", withBroadcastJoin(), 2, 2, 2); // TODO: support complex inequality join clauses: https://github.com/trinodb/trino/issues/5755 assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin AND vmax - 1", withBroadcastJoin(), 1, 3, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin + 1 AND vmax", withBroadcastJoin(), 1, 3, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin + 1 AND vmax - 1", withBroadcastJoin(), 0, 5, 2); assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin AND vmax - 1", withBroadcastJoin(), 1, 3, 2); assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin + 1 AND vmax", withBroadcastJoin(), 1, 3, 2); assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin + 1 AND vmax - 1", withBroadcastJoin(), 0, 5, 2); // TODO: make sure it works after https://github.com/trinodb/trino/issues/5777 is fixed assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin AND v <= vmax - 1", withBroadcastJoin(), 1, 1, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin + 1 AND v <= vmax", withBroadcastJoin(), 1, 1, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin + 1 AND v <= vmax - 1", withBroadcastJoin(), 0, 0, 2); // TODO: support complex inequality join clauses: https://github.com/trinodb/trino/issues/5755 assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin AND v <= vmax - 1", withBroadcastJoin(), 1, 3, 2); assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin + 1 AND v <= vmax", withBroadcastJoin(), 1, 3, 2); assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin + 1 AND v <= vmax - 1", withBroadcastJoin(), 0, 5, 2); assertDynamicFiltering("SELECT * FROM probe WHERE v <= (SELECT max(vmax) FROM build)", withBroadcastJoin(), 3, 3, 2); assertDynamicFiltering("SELECT * FROM probe JOIN build ON v IS NOT DISTINCT FROM vmin", withBroadcastJoin(), 2, 2, 2); } @Test public void testIsNotDistinctFromNaN() { assertUpdate("DROP TABLE IF EXISTS probe_nan"); assertUpdate("CREATE TABLE probe_nan (v DOUBLE)"); assertUpdate("INSERT INTO probe_nan VALUES 0, 1, 2, NULL, nan()", 5); assertUpdate("DROP TABLE IF EXISTS build_nan"); assertUpdate("CREATE TABLE build_nan (v DOUBLE)"); assertUpdate("INSERT INTO build_nan VALUES 1, NULL, nan()", 3); assertDynamicFiltering("SELECT * FROM probe_nan p JOIN build_nan b ON p.v IS NOT DISTINCT FROM b.v", withBroadcastJoin(), 3, 5, 3); assertDynamicFiltering("SELECT * FROM probe_nan p JOIN build_nan b ON p.v = b.v", withBroadcastJoin(), 1, 1, 3); } @Test public void testCrossJoinLargeBuildSideDynamicFiltering() { // Probe-side is fully scanned because the build-side is too large for dynamic filtering: assertDynamicFiltering( "SELECT * FROM orders o, customer c WHERE o.custkey < c.custkey AND c.name < 'Customer#000001000' AND o.custkey > 1000", withBroadcastJoin(), 0, ORDERS_COUNT, CUSTOMER_COUNT); } private void assertDynamicFiltering(@Language("SQL") String selectQuery, Session session, int expectedRowCount, int... expectedOperatorRowsRead) { ResultWithQueryId<MaterializedResult> result = getDistributedQueryRunner().executeWithQueryId(session, selectQuery); assertEquals(result.getResult().getRowCount(), expectedRowCount); assertEquals(getOperatorRowsRead(getDistributedQueryRunner(), result.getQueryId()), Ints.asList(expectedOperatorRowsRead)); } private Session withBroadcastJoin() { return Session.builder(getSession()) .setSystemProperty(JOIN_DISTRIBUTION_TYPE, BROADCAST.name()) .build(); } private Session withLargeDynamicFilters() { return Session.builder(getSession()) .setSystemProperty(JOIN_DISTRIBUTION_TYPE, BROADCAST.name()) .setSystemProperty(ENABLE_LARGE_DYNAMIC_FILTERS, "true") .build(); } private Session withBroadcastJoinNonReordering() { return Session.builder(getSession()) .setSystemProperty(JOIN_DISTRIBUTION_TYPE, BROADCAST.name()) .setSystemProperty(JOIN_REORDERING_STRATEGY, NONE.name()) .build(); } private Session withPartitionedJoin() { return Session.builder(getSession()) .setSystemProperty(JOIN_DISTRIBUTION_TYPE, PARTITIONED.name()) .build(); } private static List<Integer> getOperatorRowsRead(DistributedQueryRunner runner, QueryId queryId) { QueryStats stats = runner.getCoordinator().getQueryManager().getFullQueryInfo(queryId).getQueryStats(); return stats.getOperatorSummaries() .stream() .filter(summary -> summary.getOperatorType().contains("Scan")) .map(OperatorStats::getInputPositions) .map(Math::toIntExact) .collect(toImmutableList()); } @Test public void testJoinDynamicFilteringMultiJoin() { assertUpdate("CREATE TABLE t0 (k0 integer, v0 real)"); assertUpdate("CREATE TABLE t1 (k1 integer, v1 real)"); assertUpdate("CREATE TABLE t2 (k2 integer, v2 real)"); assertUpdate("INSERT INTO t0 VALUES (1, 1.0)", 1); assertUpdate("INSERT INTO t1 VALUES (1, 2.0)", 1); assertUpdate("INSERT INTO t2 VALUES (1, 3.0)", 1); String query = "SELECT k0, k1, k2 FROM t0, t1, t2 WHERE (k0 = k1) AND (k0 = k2) AND (v0 + v1 = v2)"; Session session = Session.builder(getSession()) .setSystemProperty(JOIN_DISTRIBUTION_TYPE, FeaturesConfig.JoinDistributionType.BROADCAST.name()) .setSystemProperty(JOIN_REORDERING_STRATEGY, FeaturesConfig.JoinReorderingStrategy.NONE.name()) .build(); assertQuery(session, query, "SELECT 1, 1, 1"); } @Test public void testCreateTableWithNoData() { assertUpdate("CREATE TABLE test_empty (a BIGINT)"); assertQueryResult("SELECT count(*) FROM test_empty", 0L); assertQueryResult("INSERT INTO test_empty SELECT nationkey FROM tpch.tiny.nation", 25L); assertQueryResult("SELECT count(*) FROM test_empty", 25L); } @Test public void testCreateFilteredOutTable() { assertUpdate("CREATE TABLE filtered_out AS SELECT nationkey FROM tpch.tiny.nation WHERE nationkey < 0", "SELECT count(nationkey) FROM nation WHERE nationkey < 0"); assertQueryResult("SELECT count(*) FROM filtered_out", 0L); assertQueryResult("INSERT INTO filtered_out SELECT nationkey FROM tpch.tiny.nation", 25L); assertQueryResult("SELECT count(*) FROM filtered_out", 25L); } @Test public void testSelectFromEmptyTable() { assertUpdate("CREATE TABLE test_select_empty AS SELECT * FROM tpch.tiny.nation WHERE nationkey > 1000", "SELECT count(*) FROM nation WHERE nationkey > 1000"); assertQueryResult("SELECT count(*) FROM test_select_empty", 0L); } @Test public void testSelectSingleRow() { assertQuery("SELECT * FROM tpch.tiny.nation WHERE nationkey = 1", "SELECT * FROM nation WHERE nationkey = 1"); } @Test public void testSelectColumnsSubset() { assertQuery("SELECT nationkey, regionkey FROM tpch.tiny.nation ORDER BY nationkey", "SELECT nationkey, regionkey FROM nation ORDER BY nationkey"); } @Test public void testCreateSchema() { assertQueryFails("DROP SCHEMA schema1", "line 1:1: Schema 'memory.schema1' does not exist"); assertUpdate("CREATE SCHEMA schema1"); assertQueryFails("CREATE SCHEMA schema1", "line 1:1: Schema 'memory.schema1' already exists"); assertUpdate("CREATE TABLE schema1.x(t int)"); assertQueryFails("DROP SCHEMA schema1", "Schema not empty: schema1"); assertUpdate("DROP TABLE schema1.x"); assertUpdate("DROP SCHEMA schema1"); assertQueryFails("DROP SCHEMA schema1", "line 1:1: Schema 'memory.schema1' does not exist"); assertUpdate("DROP SCHEMA IF EXISTS schema1"); } @Test public void testCreateTableInNonDefaultSchema() { assertUpdate("CREATE SCHEMA schema1"); assertUpdate("CREATE SCHEMA schema2"); assertQueryResult("SHOW SCHEMAS", "default", "information_schema", "schema1", "schema2"); assertUpdate("CREATE TABLE schema1.nation AS SELECT * FROM tpch.tiny.nation WHERE nationkey % 2 = 0", "SELECT count(*) FROM nation WHERE MOD(nationkey, 2) = 0"); assertUpdate("CREATE TABLE schema2.nation AS SELECT * FROM tpch.tiny.nation WHERE nationkey % 2 = 1", "SELECT count(*) FROM nation WHERE MOD(nationkey, 2) = 1"); assertQueryResult("SELECT count(*) FROM schema1.nation", 13L); assertQueryResult("SELECT count(*) FROM schema2.nation", 12L); } @Test public void testCreateTableAndViewInNotExistSchema() { int tablesBeforeCreate = listMemoryTables().size(); assertQueryFails("CREATE TABLE schema3.test_table3 (x date)", "Schema schema3 not found"); assertQueryFails("CREATE VIEW schema4.test_view4 AS SELECT 123 x", "Schema schema4 not found"); assertQueryFails("CREATE OR REPLACE VIEW schema5.test_view5 AS SELECT 123 x", "Schema schema5 not found"); int tablesAfterCreate = listMemoryTables().size(); assertEquals(tablesBeforeCreate, tablesAfterCreate); } @Test public void testRenameTable() { assertUpdate("CREATE TABLE test_table_to_be_renamed (a BIGINT)"); assertQueryFails("ALTER TABLE test_table_to_be_renamed RENAME TO memory.test_schema_not_exist.test_table_renamed", "Schema test_schema_not_exist not found"); assertUpdate("ALTER TABLE test_table_to_be_renamed RENAME TO test_table_renamed"); assertQueryResult("SELECT count(*) FROM test_table_renamed", 0L); assertUpdate("CREATE SCHEMA test_different_schema"); assertUpdate("ALTER TABLE test_table_renamed RENAME TO test_different_schema.test_table_renamed"); assertQueryResult("SELECT count(*) FROM test_different_schema.test_table_renamed", 0L); assertUpdate("DROP TABLE test_different_schema.test_table_renamed"); assertUpdate("DROP SCHEMA test_different_schema"); } @Test public void testViews() { @Language("SQL") String query = "SELECT orderkey, orderstatus, totalprice / 2 half FROM orders"; assertUpdate("CREATE VIEW test_view AS SELECT 123 x"); assertUpdate("CREATE OR REPLACE VIEW test_view AS " + query); assertQueryFails("CREATE TABLE test_view (x date)", "View \\[default.test_view] already exists"); assertQueryFails("CREATE VIEW test_view AS SELECT 123 x", "View already exists: default.test_view"); assertQuery("SELECT * FROM test_view", query); assertTrue(computeActual("SHOW TABLES").getOnlyColumnAsSet().contains("test_view")); assertUpdate("DROP VIEW test_view"); assertQueryFails("DROP VIEW test_view", "line 1:1: View 'memory.default.test_view' does not exist"); } @Test public void testRenameView() { @Language("SQL") String query = "SELECT orderkey, orderstatus, totalprice / 2 half FROM orders"; assertUpdate("CREATE VIEW test_view_to_be_renamed AS " + query); assertQueryFails("ALTER VIEW test_view_to_be_renamed RENAME TO memory.test_schema_not_exist.test_view_renamed", "Schema test_schema_not_exist not found"); assertUpdate("ALTER VIEW test_view_to_be_renamed RENAME TO test_view_renamed"); assertQuery("SELECT * FROM test_view_renamed", query); assertUpdate("CREATE SCHEMA test_different_schema"); assertUpdate("ALTER VIEW test_view_renamed RENAME TO test_different_schema.test_view_renamed"); assertQuery("SELECT * FROM test_different_schema.test_view_renamed", query); assertUpdate("DROP VIEW test_different_schema.test_view_renamed"); assertUpdate("DROP SCHEMA test_different_schema"); } private List<QualifiedObjectName> listMemoryTables() { return getQueryRunner().listTables(getSession(), "memory", "default"); } private void assertQueryResult(@Language("SQL") String sql, Object... expected) { MaterializedResult rows = computeActual(sql); assertEquals(rows.getRowCount(), expected.length); for (int i = 0; i < expected.length; i++) { MaterializedRow materializedRow = rows.getMaterializedRows().get(i); int fieldCount = materializedRow.getFieldCount(); assertEquals(fieldCount, 1, format("Expected only one column, but got '%d'", fieldCount)); Object value = materializedRow.getField(0); assertEquals(value, expected[i]); assertEquals(materializedRow.getFieldCount(), 1); } } }
Move testJoinDynamicFilteringMultiJoin above helper methods
plugin/trino-memory/src/test/java/io/trino/plugin/memory/TestMemorySmoke.java
Move testJoinDynamicFilteringMultiJoin above helper methods
<ide><path>lugin/trino-memory/src/test/java/io/trino/plugin/memory/TestMemorySmoke.java <ide> ORDERS_COUNT, CUSTOMER_COUNT); <ide> } <ide> <add> @Test <add> public void testJoinDynamicFilteringMultiJoin() <add> { <add> assertUpdate("CREATE TABLE t0 (k0 integer, v0 real)"); <add> assertUpdate("CREATE TABLE t1 (k1 integer, v1 real)"); <add> assertUpdate("CREATE TABLE t2 (k2 integer, v2 real)"); <add> assertUpdate("INSERT INTO t0 VALUES (1, 1.0)", 1); <add> assertUpdate("INSERT INTO t1 VALUES (1, 2.0)", 1); <add> assertUpdate("INSERT INTO t2 VALUES (1, 3.0)", 1); <add> <add> String query = "SELECT k0, k1, k2 FROM t0, t1, t2 WHERE (k0 = k1) AND (k0 = k2) AND (v0 + v1 = v2)"; <add> Session session = Session.builder(getSession()) <add> .setSystemProperty(JOIN_DISTRIBUTION_TYPE, FeaturesConfig.JoinDistributionType.BROADCAST.name()) <add> .setSystemProperty(JOIN_REORDERING_STRATEGY, FeaturesConfig.JoinReorderingStrategy.NONE.name()) <add> .build(); <add> assertQuery(session, query, "SELECT 1, 1, 1"); <add> } <add> <ide> private void assertDynamicFiltering(@Language("SQL") String selectQuery, Session session, int expectedRowCount, int... expectedOperatorRowsRead) <ide> { <ide> ResultWithQueryId<MaterializedResult> result = getDistributedQueryRunner().executeWithQueryId(session, selectQuery); <ide> .map(OperatorStats::getInputPositions) <ide> .map(Math::toIntExact) <ide> .collect(toImmutableList()); <del> } <del> <del> @Test <del> public void testJoinDynamicFilteringMultiJoin() <del> { <del> assertUpdate("CREATE TABLE t0 (k0 integer, v0 real)"); <del> assertUpdate("CREATE TABLE t1 (k1 integer, v1 real)"); <del> assertUpdate("CREATE TABLE t2 (k2 integer, v2 real)"); <del> assertUpdate("INSERT INTO t0 VALUES (1, 1.0)", 1); <del> assertUpdate("INSERT INTO t1 VALUES (1, 2.0)", 1); <del> assertUpdate("INSERT INTO t2 VALUES (1, 3.0)", 1); <del> <del> String query = "SELECT k0, k1, k2 FROM t0, t1, t2 WHERE (k0 = k1) AND (k0 = k2) AND (v0 + v1 = v2)"; <del> Session session = Session.builder(getSession()) <del> .setSystemProperty(JOIN_DISTRIBUTION_TYPE, FeaturesConfig.JoinDistributionType.BROADCAST.name()) <del> .setSystemProperty(JOIN_REORDERING_STRATEGY, FeaturesConfig.JoinReorderingStrategy.NONE.name()) <del> .build(); <del> assertQuery(session, query, "SELECT 1, 1, 1"); <ide> } <ide> <ide> @Test
Java
apache-2.0
1379854e5e92926b855b894c9685fd9dad38b881
0
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.core; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.DOMUtil; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import java.util.*; import static java.util.Collections.unmodifiableList; import static java.util.Collections.unmodifiableMap; /** * An Object which represents a Plugin of any type * @version $Id$ */ public class PluginInfo { public final String name, className, type; public final NamedList initArgs; public final Map<String, String> attributes; public final List<PluginInfo> children; public PluginInfo(String type, Map<String, String> attrs ,NamedList initArgs, List<PluginInfo> children) { this.type = type; this.name = attrs.get("name"); this.className = attrs.get("class"); this.initArgs = initArgs; attributes = unmodifiableMap(attrs); this.children = children == null ? Collections.<PluginInfo>emptyList(): unmodifiableList(children); } public PluginInfo(Node node, String err, boolean requireName, boolean requireClass) { type = node.getNodeName(); name = DOMUtil.getAttr(node, "name", requireName ? err : null); className = DOMUtil.getAttr(node, "class", requireClass ? err : null); initArgs = DOMUtil.childNodesToNamedList(node); attributes = unmodifiableMap(DOMUtil.toMap(node.getAttributes())); children = loadSubPlugins(node); } private List<PluginInfo> loadSubPlugins(Node node) { List<PluginInfo> children = null; try { //if there is another sub tag with a 'class' attribute that has to be another plugin NodeList nodes = (NodeList) Config.xpathFactory.newXPath().evaluate("*[@class]",node, XPathConstants.NODESET); if(nodes.getLength() > 0){ children = new ArrayList<PluginInfo>(nodes.getLength()); for (int i=0; i<nodes.getLength(); i++) { PluginInfo pluginInfo = new PluginInfo(nodes.item(i), null, false, false); if (pluginInfo.isEnabled()) children.add(pluginInfo); } } } catch (XPathExpressionException e) { } return children == null ? Collections.<PluginInfo>emptyList(): unmodifiableList(children); } @Override public String toString() { StringBuilder sb = new StringBuilder("{"); if (type != null) sb.append("type = " + type + ","); if (name != null) sb.append("name = " + name + ","); if (className != null) sb.append("class = " + className + ","); if (initArgs.size() > 0) sb.append("args = " + initArgs); sb.append("}"); return sb.toString(); } public boolean isEnabled(){ String enable = attributes.get("enable"); return enable == null || Boolean.parseBoolean(enable); } public boolean isDefault() { return Boolean.parseBoolean(attributes.get("default")); } }
src/java/org/apache/solr/core/PluginInfo.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.core; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.DOMUtil; import org.w3c.dom.Node; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import java.util.*; import static java.util.Collections.unmodifiableList; import static java.util.Collections.unmodifiableMap; /** * An Object which represents a Plugin of any type * @version $Id$ */ public class PluginInfo { public final String name, className, type; public final NamedList initArgs; public final Map<String, String> attributes; public final List<PluginInfo> children; public PluginInfo(String type, Map<String, String> attrs ,NamedList initArgs, List<PluginInfo> children) { this.type = type; this.name = attrs.get("name"); this.className = attrs.get("class"); this.initArgs = initArgs; attributes = unmodifiableMap(attrs); this.children = children == null ? Collections.<PluginInfo>emptyList(): unmodifiableList(children); } public PluginInfo(Node node, String err, boolean requireName, boolean requireClass) { type = node.getNodeName(); name = DOMUtil.getAttr(node, "name", requireName ? err : null); className = DOMUtil.getAttr(node, "class", requireClass ? err : null); initArgs = DOMUtil.childNodesToNamedList(node); Map<String, String> m = new HashMap<String, String>(); NamedNodeMap nnm = node.getAttributes(); for (int i = 0; i < nnm.getLength(); i++) { String name = nnm.item(i).getNodeName(); m.put(name, nnm.item(i).getNodeValue()); } attributes = unmodifiableMap(m); children = loadSubPlugins(node); } private List<PluginInfo> loadSubPlugins(Node node) { List<PluginInfo> children = null; try { //if there is another sub tag with a 'class' attribute that has to be another plugin NodeList nodes = (NodeList) Config.xpathFactory.newXPath().evaluate("*[@class]",node, XPathConstants.NODESET); if(nodes.getLength() > 0){ children = new ArrayList<PluginInfo>(nodes.getLength()); for (int i=0; i<nodes.getLength(); i++) { PluginInfo pluginInfo = new PluginInfo(nodes.item(i), null, false, false); if (pluginInfo.isEnabled()) children.add(pluginInfo); } } } catch (XPathExpressionException e) { } return children == null ? Collections.<PluginInfo>emptyList(): unmodifiableList(children); } @Override public String toString() { StringBuilder sb = new StringBuilder("{"); if (type != null) sb.append("type = " + type + ","); if (name != null) sb.append("name = " + name + ","); if (className != null) sb.append("class = " + className + ","); if (initArgs.size() > 0) sb.append("args = " + initArgs); sb.append("}"); return sb.toString(); } public boolean isEnabled(){ String enable = attributes.get("enable"); return enable == null || Boolean.parseBoolean(enable); } public boolean isDefault() { return Boolean.parseBoolean(attributes.get("default")); } }
use DOMUtil git-svn-id: 3b1ff1236863b4d63a22e4dae568675c2e247730@817210 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/solr/core/PluginInfo.java
use DOMUtil
<ide><path>rc/java/org/apache/solr/core/PluginInfo.java <ide> import org.apache.solr.common.util.NamedList; <ide> import org.apache.solr.common.util.DOMUtil; <ide> import org.w3c.dom.Node; <del>import org.w3c.dom.NamedNodeMap; <ide> import org.w3c.dom.NodeList; <ide> <ide> import javax.xml.xpath.XPathConstants; <ide> name = DOMUtil.getAttr(node, "name", requireName ? err : null); <ide> className = DOMUtil.getAttr(node, "class", requireClass ? err : null); <ide> initArgs = DOMUtil.childNodesToNamedList(node); <del> Map<String, String> m = new HashMap<String, String>(); <del> NamedNodeMap nnm = node.getAttributes(); <del> for (int i = 0; i < nnm.getLength(); i++) { <del> String name = nnm.item(i).getNodeName(); <del> m.put(name, nnm.item(i).getNodeValue()); <del> } <del> attributes = unmodifiableMap(m); <add> attributes = unmodifiableMap(DOMUtil.toMap(node.getAttributes())); <ide> children = loadSubPlugins(node); <ide> } <ide>
Java
apache-2.0
5917792d8801ebe143167259c10cfe35018622a3
0
JFixby/libgdx,JFixby/libgdx,JFixby/libgdx,JFixby/libgdx,JFixby/libgdx,JFixby/libgdx,JFixby/libgdx,JFixby/libgdx
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.graphics.glutils; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.BufferUtils; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.StreamUtils; /** Class for encoding and decoding ETC1 compressed images. Also provides methods to add a PKM header. * @author mzechner */ public class ETC1 { /** The PKM header size in bytes **/ public static int PKM_HEADER_SIZE = 16; public static int ETC1_RGB8_OES = 0x00008d64; /** Class for storing ETC1 compressed image data. * @author mzechner */ public final static class ETC1Data implements Disposable { /** the width in pixels **/ public final int width; /** the height in pixels **/ public final int height; /** the optional PKM header and compressed image data **/ public final ByteBuffer compressedData; /** the offset in bytes to the actual compressed data. Might be 16 if this contains a PKM header, 0 otherwise **/ public final int dataOffset; public ETC1Data (int width, int height, ByteBuffer compressedData, int dataOffset) { this.width = width; this.height = height; this.compressedData = compressedData; this.dataOffset = dataOffset; checkNPOT(); } public ETC1Data (ETC1Data specs) { this.width = specs.width; this.height = specs.height; this.compressedData = specs.compressedData; this.dataOffset = specs.dataOffset; checkNPOT(); } @Deprecated // Backward compatibility, please use ETC1Data.read(pkmFile) instead public ETC1Data (FileHandle pkmFile) { this(ETC1Data.read(pkmFile)); } public static ETC1Data read (FileHandle pkmFile) { InputStream fileStream = null; try { fileStream = pkmFile.read(); final ETC1Data data = read(fileStream); return data; } catch (Exception e) { throw new GdxRuntimeException("Couldn't load pkm from " + pkmFile, e); } finally { StreamUtils.closeQuietly(fileStream); } } public static ETC1Data read (java.io.InputStream inputStream) { byte[] buffer = new byte[1024 * 10]; DataInputStream dataStream = null; GZIPInputStream gzipStream = null; BufferedInputStream bufferedStream = null; ByteBuffer compressedData = null; int width; int height; int dataOffset; try { gzipStream = new GZIPInputStream(inputStream); bufferedStream = new BufferedInputStream(gzipStream); dataStream = new DataInputStream(bufferedStream); int fileSize = dataStream.readInt(); compressedData = BufferUtils.newUnsafeByteBuffer(fileSize); int readBytes = 0; while ((readBytes = dataStream.read(buffer)) != -1) { compressedData.put(buffer, 0, readBytes); } compressedData.position(0); compressedData.limit(compressedData.capacity()); } catch (Exception e) { throw new GdxRuntimeException("Couldn't load pkm", e); } finally { StreamUtils.closeQuietly(dataStream); StreamUtils.closeQuietly(bufferedStream); StreamUtils.closeQuietly(gzipStream); } width = getWidthPKM(compressedData, 0); height = getHeightPKM(compressedData, 0); dataOffset = PKM_HEADER_SIZE; compressedData.position(dataOffset); ETC1Data destination = new ETC1Data(width, height, compressedData, dataOffset); return destination; } private void checkNPOT () { if (!MathUtils.isPowerOfTwo(width) || !MathUtils.isPowerOfTwo(height)) { System.out.println("ETC1Data " + "warning: non-power-of-two ETC1 textures may crash the driver of PowerVR GPUs"); } } /** @return whether this ETC1Data has a PKM header */ public boolean hasPKMHeader () { return dataOffset == 16; } /** Writes the ETC1Data with a PKM header to the given file. * @param file the file. */ public void write (FileHandle file) { OutputStream fileStream = null; try { fileStream = file.write(false); write(fileStream); fileStream.flush(); } catch (Exception e) { throw new GdxRuntimeException("Couldn't write PKM file to '" + file + "'", e); } finally { StreamUtils.closeQuietly(fileStream); } } /** Writes the ETC1Data with a PKM header to the outputStream. * @param outputStream java.io.OutputStream. */ public void write (OutputStream outputStream) { DataOutputStream dataStream = null; GZIPOutputStream gzipStream = null; byte[] buffer = new byte[10 * 1024]; int writtenBytes = 0; compressedData.position(0); compressedData.limit(compressedData.capacity()); try { gzipStream = new GZIPOutputStream(outputStream); dataStream = new DataOutputStream(gzipStream); dataStream.writeInt(compressedData.capacity()); while (writtenBytes != compressedData.capacity()) { int bytesToWrite = Math.min(compressedData.remaining(), buffer.length); compressedData.get(buffer, 0, bytesToWrite); dataStream.write(buffer, 0, bytesToWrite); writtenBytes += bytesToWrite; } dataStream.flush(); gzipStream.flush(); } catch (Exception e) { throw new GdxRuntimeException("Couldn't write PKM", e); } finally { StreamUtils.closeQuietly(dataStream); StreamUtils.closeQuietly(gzipStream); } compressedData.position(dataOffset); compressedData.limit(compressedData.capacity()); } /** Releases the native resources of the ETC1Data instance. */ public void dispose () { BufferUtils.disposeUnsafeByteBuffer(compressedData); } public String toString () { if (hasPKMHeader()) { return (ETC1.isValidPKM(compressedData, 0) ? "valid" : "invalid") + " pkm [" + ETC1.getWidthPKM(compressedData, 0) + "x" + ETC1.getHeightPKM(compressedData, 0) + "], compressed: " + (compressedData.capacity() - ETC1.PKM_HEADER_SIZE); } else { return "raw [" + width + "x" + height + "], compressed: " + (compressedData.capacity() - ETC1.PKM_HEADER_SIZE); } } } private static int getPixelSize (Format format) { if (format == Format.RGB565) return 2; if (format == Format.RGB888) return 3; throw new GdxRuntimeException("Can only handle RGB565 or RGB888 images"); } /** Encodes the image via the ETC1 compression scheme. Only {@link Format#RGB565} and {@link Format#RGB888} are supported. * @param pixmap the {@link Pixmap} * @return the {@link ETC1Data} */ public static ETC1Data encodeImage (Pixmap pixmap) { int pixelSize = getPixelSize(pixmap.getFormat()); ByteBuffer compressedData = encodeImage(pixmap.getPixels(), 0, pixmap.getWidth(), pixmap.getHeight(), pixelSize); BufferUtils.newUnsafeByteBuffer(compressedData); return new ETC1Data(pixmap.getWidth(), pixmap.getHeight(), compressedData, 0); } /** Encodes the image via the ETC1 compression scheme. Only {@link Format#RGB565} and {@link Format#RGB888} are supported. Adds * a PKM header in front of the compressed image data. * @param pixmap the {@link Pixmap} * @return the {@link ETC1Data} */ public static ETC1Data encodeImagePKM (Pixmap pixmap) { int pixelSize = getPixelSize(pixmap.getFormat()); ByteBuffer compressedData = encodeImagePKM(pixmap.getPixels(), 0, pixmap.getWidth(), pixmap.getHeight(), pixelSize); BufferUtils.newUnsafeByteBuffer(compressedData); return new ETC1Data(pixmap.getWidth(), pixmap.getHeight(), compressedData, 16); } /** Takes ETC1 compressed image data and converts it to a {@link Format#RGB565} or {@link Format#RGB888} {@link Pixmap}. Does * not modify the ByteBuffer's position or limit. * @param etc1Data the {@link ETC1Data} instance * @param format either {@link Format#RGB565} or {@link Format#RGB888} * @return the Pixmap */ public static Pixmap decodeImage (ETC1Data etc1Data, Format format) { int dataOffset = 0; int width = 0; int height = 0; if (etc1Data.hasPKMHeader()) { dataOffset = 16; width = ETC1.getWidthPKM(etc1Data.compressedData, 0); height = ETC1.getHeightPKM(etc1Data.compressedData, 0); } else { dataOffset = 0; width = etc1Data.width; height = etc1Data.height; } int pixelSize = getPixelSize(format); Pixmap pixmap = new Pixmap(width, height, format); decodeImage(etc1Data.compressedData, dataOffset, pixmap.getPixels(), 0, width, height, pixelSize); return pixmap; } // @off /*JNI #include <etc1/etc1_utils.h> #include <stdlib.h> */ /** @param width the width in pixels * @param height the height in pixels * @return the number of bytes needed to store the compressed data */ public static native int getCompressedDataSize (int width, int height); /* return etc1_get_encoded_data_size(width, height); */ /** Writes a PKM header to the {@link ByteBuffer}. Does not modify the position or limit of the ByteBuffer. * @param header the direct native order {@link ByteBuffer} * @param offset the offset to the header in bytes * @param width the width in pixels * @param height the height in pixels */ public static native void formatHeader (ByteBuffer header, int offset, int width, int height); /* etc1_pkm_format_header((etc1_byte*)header + offset, width, height); */ /** @param header direct native order {@link ByteBuffer} holding the PKM header * @param offset the offset in bytes to the PKM header from the ByteBuffer's start * @return the width stored in the PKM header */ static native int getWidthPKM (ByteBuffer header, int offset); /* return etc1_pkm_get_width((etc1_byte*)header + offset); */ /** @param header direct native order {@link ByteBuffer} holding the PKM header * @param offset the offset in bytes to the PKM header from the ByteBuffer's start * @return the height stored in the PKM header */ static native int getHeightPKM (ByteBuffer header, int offset); /* return etc1_pkm_get_height((etc1_byte*)header + offset); */ /** @param header direct native order {@link ByteBuffer} holding the PKM header * @param offset the offset in bytes to the PKM header from the ByteBuffer's start * @return the width stored in the PKM header */ static native boolean isValidPKM (ByteBuffer header, int offset); /* return etc1_pkm_is_valid((etc1_byte*)header + offset) != 0?true:false; */ /** Decodes the compressed image data to RGB565 or RGB888 pixel data. Does not modify the position or limit of the * {@link ByteBuffer} instances. * @param compressedData the compressed image data in a direct native order {@link ByteBuffer} * @param offset the offset in bytes to the image data from the start of the buffer * @param decodedData the decoded data in a direct native order ByteBuffer, must hold width * height * pixelSize bytes. * @param offsetDec the offset in bytes to the decoded image data. * @param width the width in pixels * @param height the height in pixels * @param pixelSize the pixel size, either 2 (RBG565) or 3 (RGB888) */ private static native void decodeImage (ByteBuffer compressedData, int offset, ByteBuffer decodedData, int offsetDec, int width, int height, int pixelSize); /* etc1_decode_image((etc1_byte*)compressedData + offset, (etc1_byte*)decodedData + offsetDec, width, height, pixelSize, width * pixelSize); */ /** Encodes the image data given as RGB565 or RGB888. Does not modify the position or limit of the {@link ByteBuffer}. * @param imageData the image data in a direct native order {@link ByteBuffer} * @param offset the offset in bytes to the image data from the start of the buffer * @param width the width in pixels * @param height the height in pixels * @param pixelSize the pixel size, either 2 (RGB565) or 3 (RGB888) * @return a new direct native order ByteBuffer containing the compressed image data */ private static native ByteBuffer encodeImage (ByteBuffer imageData, int offset, int width, int height, int pixelSize); /* int compressedSize = etc1_get_encoded_data_size(width, height); etc1_byte* compressedData = (etc1_byte*)malloc(compressedSize); etc1_encode_image((etc1_byte*)imageData + offset, width, height, pixelSize, width * pixelSize, compressedData); return env->NewDirectByteBuffer(compressedData, compressedSize); */ /** Encodes the image data given as RGB565 or RGB888. Does not modify the position or limit of the {@link ByteBuffer}. * @param imageData the image data in a direct native order {@link ByteBuffer} * @param offset the offset in bytes to the image data from the start of the buffer * @param width the width in pixels * @param height the height in pixels * @param pixelSize the pixel size, either 2 (RGB565) or 3 (RGB888) * @return a new direct native order ByteBuffer containing the compressed image data */ private static native ByteBuffer encodeImagePKM (ByteBuffer imageData, int offset, int width, int height, int pixelSize); /* int compressedSize = etc1_get_encoded_data_size(width, height); etc1_byte* compressed = (etc1_byte*)malloc(compressedSize + ETC_PKM_HEADER_SIZE); etc1_pkm_format_header(compressed, width, height); etc1_encode_image((etc1_byte*)imageData + offset, width, height, pixelSize, width * pixelSize, compressed + ETC_PKM_HEADER_SIZE); return env->NewDirectByteBuffer(compressed, compressedSize + ETC_PKM_HEADER_SIZE); */ }
gdx/src/com/badlogic/gdx/graphics/glutils/ETC1.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.graphics.glutils; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.BufferUtils; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.StreamUtils; /** Class for encoding and decoding ETC1 compressed images. Also provides methods to add a PKM header. * @author mzechner */ public class ETC1 { /** The PKM header size in bytes **/ public static int PKM_HEADER_SIZE = 16; public static int ETC1_RGB8_OES = 0x00008d64; /** Class for storing ETC1 compressed image data. * @author mzechner */ public static class ETC1Data implements Disposable { /** the width in pixels **/ public final int width; /** the height in pixels **/ public final int height; /** the optional PKM header and compressed image data **/ public final ByteBuffer compressedData; /** the offset in bytes to the actual compressed data. Might be 16 if this contains a PKM header, 0 otherwise **/ public final int dataOffset; public ETC1Data (int width, int height, ByteBuffer compressedData, int dataOffset) { this.width = width; this.height = height; this.compressedData = compressedData; this.dataOffset = dataOffset; checkNPOT(); } public ETC1Data (ETC1Data specs) { this.width = specs.width; this.height = specs.height; this.compressedData = specs.compressedData; this.dataOffset = specs.dataOffset; checkNPOT(); } @Deprecated // Backward compatibility, please use ETC1Data.read(pkmFile) instead public ETC1Data (FileHandle pkmFile) { this(ETC1Data.read(pkmFile)); } public static ETC1Data read (FileHandle pkmFile) { InputStream fileStream = null; try { fileStream = pkmFile.read(); final ETC1Data data = read(fileStream); return data; } catch (Exception e) { throw new GdxRuntimeException("Couldn't load pkm from " + pkmFile, e); } finally { StreamUtils.closeQuietly(fileStream); } } public static ETC1Data read (java.io.InputStream inputStream) { byte[] buffer = new byte[1024 * 10]; DataInputStream dataStream = null; GZIPInputStream gzipStream = null; BufferedInputStream bufferedStream = null; ByteBuffer compressedData = null; int width; int height; int dataOffset; try { gzipStream = new GZIPInputStream(inputStream); bufferedStream = new BufferedInputStream(gzipStream); dataStream = new DataInputStream(bufferedStream); int fileSize = dataStream.readInt(); compressedData = BufferUtils.newUnsafeByteBuffer(fileSize); int readBytes = 0; while ((readBytes = dataStream.read(buffer)) != -1) { compressedData.put(buffer, 0, readBytes); } compressedData.position(0); compressedData.limit(compressedData.capacity()); } catch (Exception e) { throw new GdxRuntimeException("Couldn't load pkm", e); } finally { StreamUtils.closeQuietly(dataStream); StreamUtils.closeQuietly(bufferedStream); StreamUtils.closeQuietly(gzipStream); } width = getWidthPKM(compressedData, 0); height = getHeightPKM(compressedData, 0); dataOffset = PKM_HEADER_SIZE; compressedData.position(dataOffset); ETC1Data destination = new ETC1Data(width, height, compressedData, dataOffset); return destination; } private void checkNPOT () { if (!MathUtils.isPowerOfTwo(width) || !MathUtils.isPowerOfTwo(height)) { System.out.println("ETC1Data " + "warning: non-power-of-two ETC1 textures may crash the driver of PowerVR GPUs"); } } /** @return whether this ETC1Data has a PKM header */ public boolean hasPKMHeader () { return dataOffset == 16; } /** Writes the ETC1Data with a PKM header to the given file. * @param file the file. */ public void write (FileHandle file) { OutputStream fileStream = null; try { fileStream = file.write(false); write(fileStream); fileStream.flush(); } catch (Exception e) { throw new GdxRuntimeException("Couldn't write PKM file to '" + file + "'", e); } finally { StreamUtils.closeQuietly(fileStream); } } /** Writes the ETC1Data with a PKM header to the outputStream. * @param outputStream java.io.OutputStream. */ public void write (OutputStream outputStream) { DataOutputStream dataStream = null; GZIPOutputStream gzipStream = null; byte[] buffer = new byte[10 * 1024]; int writtenBytes = 0; compressedData.position(0); compressedData.limit(compressedData.capacity()); try { gzipStream = new GZIPOutputStream(outputStream); dataStream = new DataOutputStream(gzipStream); dataStream.writeInt(compressedData.capacity()); while (writtenBytes != compressedData.capacity()) { int bytesToWrite = Math.min(compressedData.remaining(), buffer.length); compressedData.get(buffer, 0, bytesToWrite); dataStream.write(buffer, 0, bytesToWrite); writtenBytes += bytesToWrite; } dataStream.flush(); gzipStream.flush(); } catch (Exception e) { throw new GdxRuntimeException("Couldn't write PKM", e); } finally { StreamUtils.closeQuietly(dataStream); StreamUtils.closeQuietly(gzipStream); } compressedData.position(dataOffset); compressedData.limit(compressedData.capacity()); } /** Releases the native resources of the ETC1Data instance. */ public void dispose () { BufferUtils.disposeUnsafeByteBuffer(compressedData); } public String toString () { if (hasPKMHeader()) { return (ETC1.isValidPKM(compressedData, 0) ? "valid" : "invalid") + " pkm [" + ETC1.getWidthPKM(compressedData, 0) + "x" + ETC1.getHeightPKM(compressedData, 0) + "], compressed: " + (compressedData.capacity() - ETC1.PKM_HEADER_SIZE); } else { return "raw [" + width + "x" + height + "], compressed: " + (compressedData.capacity() - ETC1.PKM_HEADER_SIZE); } } } private static int getPixelSize (Format format) { if (format == Format.RGB565) return 2; if (format == Format.RGB888) return 3; throw new GdxRuntimeException("Can only handle RGB565 or RGB888 images"); } /** Encodes the image via the ETC1 compression scheme. Only {@link Format#RGB565} and {@link Format#RGB888} are supported. * @param pixmap the {@link Pixmap} * @return the {@link ETC1Data} */ public static ETC1Data encodeImage (Pixmap pixmap) { int pixelSize = getPixelSize(pixmap.getFormat()); ByteBuffer compressedData = encodeImage(pixmap.getPixels(), 0, pixmap.getWidth(), pixmap.getHeight(), pixelSize); BufferUtils.newUnsafeByteBuffer(compressedData); return new ETC1Data(pixmap.getWidth(), pixmap.getHeight(), compressedData, 0); } /** Encodes the image via the ETC1 compression scheme. Only {@link Format#RGB565} and {@link Format#RGB888} are supported. Adds * a PKM header in front of the compressed image data. * @param pixmap the {@link Pixmap} * @return the {@link ETC1Data} */ public static ETC1Data encodeImagePKM (Pixmap pixmap) { int pixelSize = getPixelSize(pixmap.getFormat()); ByteBuffer compressedData = encodeImagePKM(pixmap.getPixels(), 0, pixmap.getWidth(), pixmap.getHeight(), pixelSize); BufferUtils.newUnsafeByteBuffer(compressedData); return new ETC1Data(pixmap.getWidth(), pixmap.getHeight(), compressedData, 16); } /** Takes ETC1 compressed image data and converts it to a {@link Format#RGB565} or {@link Format#RGB888} {@link Pixmap}. Does * not modify the ByteBuffer's position or limit. * @param etc1Data the {@link ETC1Data} instance * @param format either {@link Format#RGB565} or {@link Format#RGB888} * @return the Pixmap */ public static Pixmap decodeImage (ETC1Data etc1Data, Format format) { int dataOffset = 0; int width = 0; int height = 0; if (etc1Data.hasPKMHeader()) { dataOffset = 16; width = ETC1.getWidthPKM(etc1Data.compressedData, 0); height = ETC1.getHeightPKM(etc1Data.compressedData, 0); } else { dataOffset = 0; width = etc1Data.width; height = etc1Data.height; } int pixelSize = getPixelSize(format); Pixmap pixmap = new Pixmap(width, height, format); decodeImage(etc1Data.compressedData, dataOffset, pixmap.getPixels(), 0, width, height, pixelSize); return pixmap; } // @off /*JNI #include <etc1/etc1_utils.h> #include <stdlib.h> */ /** @param width the width in pixels * @param height the height in pixels * @return the number of bytes needed to store the compressed data */ public static native int getCompressedDataSize (int width, int height); /* return etc1_get_encoded_data_size(width, height); */ /** Writes a PKM header to the {@link ByteBuffer}. Does not modify the position or limit of the ByteBuffer. * @param header the direct native order {@link ByteBuffer} * @param offset the offset to the header in bytes * @param width the width in pixels * @param height the height in pixels */ public static native void formatHeader (ByteBuffer header, int offset, int width, int height); /* etc1_pkm_format_header((etc1_byte*)header + offset, width, height); */ /** @param header direct native order {@link ByteBuffer} holding the PKM header * @param offset the offset in bytes to the PKM header from the ByteBuffer's start * @return the width stored in the PKM header */ static native int getWidthPKM (ByteBuffer header, int offset); /* return etc1_pkm_get_width((etc1_byte*)header + offset); */ /** @param header direct native order {@link ByteBuffer} holding the PKM header * @param offset the offset in bytes to the PKM header from the ByteBuffer's start * @return the height stored in the PKM header */ static native int getHeightPKM (ByteBuffer header, int offset); /* return etc1_pkm_get_height((etc1_byte*)header + offset); */ /** @param header direct native order {@link ByteBuffer} holding the PKM header * @param offset the offset in bytes to the PKM header from the ByteBuffer's start * @return the width stored in the PKM header */ static native boolean isValidPKM (ByteBuffer header, int offset); /* return etc1_pkm_is_valid((etc1_byte*)header + offset) != 0?true:false; */ /** Decodes the compressed image data to RGB565 or RGB888 pixel data. Does not modify the position or limit of the * {@link ByteBuffer} instances. * @param compressedData the compressed image data in a direct native order {@link ByteBuffer} * @param offset the offset in bytes to the image data from the start of the buffer * @param decodedData the decoded data in a direct native order ByteBuffer, must hold width * height * pixelSize bytes. * @param offsetDec the offset in bytes to the decoded image data. * @param width the width in pixels * @param height the height in pixels * @param pixelSize the pixel size, either 2 (RBG565) or 3 (RGB888) */ private static native void decodeImage (ByteBuffer compressedData, int offset, ByteBuffer decodedData, int offsetDec, int width, int height, int pixelSize); /* etc1_decode_image((etc1_byte*)compressedData + offset, (etc1_byte*)decodedData + offsetDec, width, height, pixelSize, width * pixelSize); */ /** Encodes the image data given as RGB565 or RGB888. Does not modify the position or limit of the {@link ByteBuffer}. * @param imageData the image data in a direct native order {@link ByteBuffer} * @param offset the offset in bytes to the image data from the start of the buffer * @param width the width in pixels * @param height the height in pixels * @param pixelSize the pixel size, either 2 (RGB565) or 3 (RGB888) * @return a new direct native order ByteBuffer containing the compressed image data */ private static native ByteBuffer encodeImage (ByteBuffer imageData, int offset, int width, int height, int pixelSize); /* int compressedSize = etc1_get_encoded_data_size(width, height); etc1_byte* compressedData = (etc1_byte*)malloc(compressedSize); etc1_encode_image((etc1_byte*)imageData + offset, width, height, pixelSize, width * pixelSize, compressedData); return env->NewDirectByteBuffer(compressedData, compressedSize); */ /** Encodes the image data given as RGB565 or RGB888. Does not modify the position or limit of the {@link ByteBuffer}. * @param imageData the image data in a direct native order {@link ByteBuffer} * @param offset the offset in bytes to the image data from the start of the buffer * @param width the width in pixels * @param height the height in pixels * @param pixelSize the pixel size, either 2 (RGB565) or 3 (RGB888) * @return a new direct native order ByteBuffer containing the compressed image data */ private static native ByteBuffer encodeImagePKM (ByteBuffer imageData, int offset, int width, int height, int pixelSize); /* int compressedSize = etc1_get_encoded_data_size(width, height); etc1_byte* compressed = (etc1_byte*)malloc(compressedSize + ETC_PKM_HEADER_SIZE); etc1_pkm_format_header(compressed, width, height); etc1_encode_image((etc1_byte*)imageData + offset, width, height, pixelSize, width * pixelSize, compressed + ETC_PKM_HEADER_SIZE); return env->NewDirectByteBuffer(compressed, compressedSize + ETC_PKM_HEADER_SIZE); */ }
put the final back
gdx/src/com/badlogic/gdx/graphics/glutils/ETC1.java
put the final back
<ide><path>dx/src/com/badlogic/gdx/graphics/glutils/ETC1.java <ide> <ide> /** Class for storing ETC1 compressed image data. <ide> * @author mzechner */ <del> public static class ETC1Data implements Disposable { <add> public final static class ETC1Data implements Disposable { <ide> /** the width in pixels **/ <ide> public final int width; <ide> /** the height in pixels **/
Java
mit
c64e47dcd686e9c67ae980c41317481e44fdd35b
0
mfietz/AntennaPod,johnjohndoe/AntennaPod,mfietz/AntennaPod,johnjohndoe/AntennaPod,mfietz/AntennaPod,johnjohndoe/AntennaPod,johnjohndoe/AntennaPod,mfietz/AntennaPod
package de.test.antennapod.util.service.download; import android.support.v4.util.ArrayMap; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.PushbackInputStream; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URLDecoder; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TimeZone; /** * A simple, tiny, nicely embeddable HTTP server in Java * <p/> * <p/> * NanoHTTPD * <p></p>Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen, 2010 by Konstantinos Togias</p> * <p/> * <p/> * <b>Features + limitations: </b> * <ul> * <p/> * <li>Only one Java file</li> * <li>Java 5 compatible</li> * <li>Released as open source, Modified BSD licence</li> * <li>No fixed config files, logging, authorization etc. (Implement yourself if you need them.)</li> * <li>Supports parameter parsing of GET and POST methods (+ rudimentary PUT support in 1.25)</li> * <li>Supports both dynamic content and file serving</li> * <li>Supports file upload (since version 1.2, 2010)</li> * <li>Supports partial content (streaming)</li> * <li>Supports ETags</li> * <li>Never caches anything</li> * <li>Doesn't limit bandwidth, request time or simultaneous connections</li> * <li>Default code serves files and shows all HTTP parameters and headers</li> * <li>File server supports directory listing, index.html and index.htm</li> * <li>File server supports partial content (streaming)</li> * <li>File server supports ETags</li> * <li>File server does the 301 redirection trick for directories without '/'</li> * <li>File server supports simple skipping for files (continue download)</li> * <li>File server serves also very long files without memory overhead</li> * <li>Contains a built-in list of most common mime types</li> * <li>All header names are converted lowercase so they don't vary between browsers/clients</li> * <p/> * </ul> * <p/> * <p/> * <b>How to use: </b> * <ul> * <p/> * <li>Subclass and implement serve() and embed to your own program</li> * <p/> * </ul> * <p/> * See the separate "LICENSE.md" file for the distribution license (Modified BSD licence) */ public abstract class NanoHTTPD { /** * Maximum time to wait on Socket.getInputStream().read() (in milliseconds) * This is required as the Keep-Alive HTTP connections would otherwise * block the socket reading thread forever (or as long the browser is open). */ private static final int SOCKET_READ_TIMEOUT = 5000; /** * Common mime type for dynamic content: plain text */ private static final String MIME_PLAINTEXT = "text/plain"; /** * Common mime type for dynamic content: html */ private static final String MIME_HTML = "text/html"; /** * Pseudo-Parameter to use to store the actual query string in the parameters map for later re-processing. */ private static final String QUERY_STRING_PARAMETER = "NanoHttpd.QUERY_STRING"; private final String hostname; private final int myPort; private ServerSocket myServerSocket; private final Set<Socket> openConnections = new HashSet<>(); private Thread myThread; /** * Pluggable strategy for asynchronously executing requests. */ private AsyncRunner asyncRunner; /** * Pluggable strategy for creating and cleaning up temporary files. */ private TempFileManagerFactory tempFileManagerFactory; /** * Constructs an HTTP server on given port. */ NanoHTTPD(int port) { this(null, port); } /** * Constructs an HTTP server on given hostname and port. */ private NanoHTTPD(String hostname, int port) { this.hostname = hostname; this.myPort = port; setTempFileManagerFactory(new DefaultTempFileManagerFactory()); setAsyncRunner(new DefaultAsyncRunner()); } private static final void safeClose(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { } } } private static final void safeClose(Socket closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { } } } private static final void safeClose(ServerSocket closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { } } } /** * Start the server. * * @throws IOException if the socket is in use. */ public void start() throws IOException { myServerSocket = new ServerSocket(); myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort)); myThread = new Thread(() -> { do { try { final Socket finalAccept = myServerSocket.accept(); registerConnection(finalAccept); finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT); final InputStream inputStream = finalAccept.getInputStream(); asyncRunner.exec(() -> { OutputStream outputStream = null; try { outputStream = finalAccept.getOutputStream(); TempFileManager tempFileManager = tempFileManagerFactory.create(); HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress()); while (!finalAccept.isClosed()) { session.execute(); } } catch (Exception e) { // When the socket is closed by the client, we throw our own SocketException // to break the "keep alive" loop above. if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) { e.printStackTrace(); } } finally { safeClose(outputStream); safeClose(inputStream); safeClose(finalAccept); unRegisterConnection(finalAccept); } }); } catch (IOException e) { } } while (!myServerSocket.isClosed()); }); myThread.setDaemon(true); myThread.setName("NanoHttpd Main Listener"); myThread.start(); } /** * Stop the server. */ public void stop() { try { safeClose(myServerSocket); closeAllConnections(); if (myThread != null) { myThread.join(); } } catch (Exception e) { e.printStackTrace(); } } /** * Registers that a new connection has been set up. * * @param socket the {@link Socket} for the connection. */ private synchronized void registerConnection(Socket socket) { openConnections.add(socket); } /** * Registers that a connection has been closed * * @param socket * the {@link Socket} for the connection. */ private synchronized void unRegisterConnection(Socket socket) { openConnections.remove(socket); } /** * Forcibly closes all connections that are open. */ private synchronized void closeAllConnections() { for (Socket socket : openConnections) { safeClose(socket); } } public final int getListeningPort() { return myServerSocket == null ? -1 : myServerSocket.getLocalPort(); } private boolean wasStarted() { return myServerSocket != null && myThread != null; } public final boolean isAlive() { return wasStarted() && !myServerSocket.isClosed() && myThread.isAlive(); } /** * Override this to customize the server. * <p/> * <p/> * (By default, this delegates to serveFile() and allows directory listing.) * * @param uri Percent-decoded URI without parameters, for example "/index.cgi" * @param method "GET", "POST" etc. * @param parms Parsed, percent decoded parameters from URI and, in case of POST, data. * @param headers Header entries, percent decoded * @return HTTP response, see class Response for details */ @Deprecated public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) { return new Response(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found"); } /** * Override this to customize the server. * <p/> * <p/> * (By default, this delegates to serveFile() and allows directory listing.) * * @param session The HTTP session * @return HTTP response, see class Response for details */ Response serve(IHTTPSession session) { Map<String, String> files = new ArrayMap<>(); Method method = session.getMethod(); if (Method.PUT.equals(method) || Method.POST.equals(method)) { try { session.parseBody(files); } catch (IOException ioe) { return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); } catch (ResponseException re) { return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage()); } } Map<String, String> parms = session.getParms(); parms.put(QUERY_STRING_PARAMETER, session.getQueryParameterString()); return serve(session.getUri(), method, session.getHeaders(), parms, files); } /** * Decode percent encoded <code>String</code> values. * * @param str the percent encoded <code>String</code> * @return expanded form of the input, for example "foo%20bar" becomes "foo bar" */ private String decodePercent(String str) { String decoded = null; try { decoded = URLDecoder.decode(str, "UTF8"); } catch (UnsupportedEncodingException ignored) { } return decoded; } /** * Decode parameters from a URL, handing the case where a single parameter name might have been * supplied several times, by return lists of values. In general these lists will contain a single * element. * * @param parms original <b>NanoHttpd</b> parameters values, as passed to the <code>serve()</code> method. * @return a map of <code>String</code> (parameter name) to <code>List&lt;String&gt;</code> (a list of the values supplied). */ protected Map<String, List<String>> decodeParameters(Map<String, String> parms) { return this.decodeParameters(parms.get(QUERY_STRING_PARAMETER)); } /** * Decode parameters from a URL, handing the case where a single parameter name might have been * supplied several times, by return lists of values. In general these lists will contain a single * element. * * @param queryString a query string pulled from the URL. * @return a map of <code>String</code> (parameter name) to <code>List&lt;String&gt;</code> (a list of the values supplied). */ private Map<String, List<String>> decodeParameters(String queryString) { Map<String, List<String>> parms = new ArrayMap<>(); if (queryString != null) { StringTokenizer st = new StringTokenizer(queryString, "&"); while (st.hasMoreTokens()) { String e = st.nextToken(); int sep = e.indexOf('='); String propertyName = (sep >= 0) ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim(); if (!parms.containsKey(propertyName)) { parms.put(propertyName, new ArrayList<>()); } String propertyValue = (sep >= 0) ? decodePercent(e.substring(sep + 1)) : null; if (propertyValue != null) { parms.get(propertyName).add(propertyValue); } } } return parms; } // ------------------------------------------------------------------------------- // // // Threading Strategy. // // ------------------------------------------------------------------------------- // /** * Pluggable strategy for asynchronously executing requests. * * @param asyncRunner new strategy for handling threads. */ private void setAsyncRunner(AsyncRunner asyncRunner) { this.asyncRunner = asyncRunner; } // ------------------------------------------------------------------------------- // // // Temp file handling strategy. // // ------------------------------------------------------------------------------- // /** * Pluggable strategy for creating and cleaning up temporary files. * * @param tempFileManagerFactory new strategy for handling temp files. */ private void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) { this.tempFileManagerFactory = tempFileManagerFactory; } /** * HTTP Request methods, with the ability to decode a <code>String</code> back to its enum value. */ public enum Method { GET, PUT, POST, DELETE, HEAD, OPTIONS; static Method lookup(String method) { for (Method m : Method.values()) { if (m.toString().equalsIgnoreCase(method)) { return m; } } return null; } } /** * Pluggable strategy for asynchronously executing requests. */ public interface AsyncRunner { void exec(Runnable code); } /** * Factory to create temp file managers. */ public interface TempFileManagerFactory { TempFileManager create(); } // ------------------------------------------------------------------------------- // /** * Temp file manager. * <p/> * <p>Temp file managers are created 1-to-1 with incoming requests, to create and cleanup * temporary files created as a result of handling the request.</p> */ public interface TempFileManager { TempFile createTempFile() throws Exception; void clear(); } /** * A temp file. * <p/> * <p>Temp files are responsible for managing the actual temporary storage and cleaning * themselves up when no longer needed.</p> */ public interface TempFile { OutputStream open(); void delete(); String getName(); } /** * Default threading strategy for NanoHttpd. * <p/> * <p>By default, the server spawns a new Thread for every incoming request. These are set * to <i>daemon</i> status, and named according to the request number. The name is * useful when profiling the application.</p> */ public static class DefaultAsyncRunner implements AsyncRunner { private long requestCount; @Override public void exec(Runnable code) { ++requestCount; Thread t = new Thread(code); t.setDaemon(true); t.setName("NanoHttpd Request Processor (#" + requestCount + ")"); t.start(); } } /** * Default strategy for creating and cleaning up temporary files. * <p/> * <p></p>This class stores its files in the standard location (that is, * wherever <code>java.io.tmpdir</code> points to). Files are added * to an internal list, and deleted when no longer needed (that is, * when <code>clear()</code> is invoked at the end of processing a * request).</p> */ public static class DefaultTempFileManager implements TempFileManager { private final String tmpdir; private final List<TempFile> tempFiles; public DefaultTempFileManager() { tmpdir = System.getProperty("java.io.tmpdir"); tempFiles = new ArrayList<>(); } @Override public TempFile createTempFile() throws Exception { DefaultTempFile tempFile = new DefaultTempFile(tmpdir); tempFiles.add(tempFile); return tempFile; } @Override public void clear() { for (TempFile file : tempFiles) { try { file.delete(); } catch (Exception ignored) { } } tempFiles.clear(); } } /** * Default strategy for creating and cleaning up temporary files. * <p/> * <p></p></[>By default, files are created by <code>File.createTempFile()</code> in * the directory specified.</p> */ public static class DefaultTempFile implements TempFile { private File file; private OutputStream fstream; public DefaultTempFile(String tempdir) throws IOException { file = File.createTempFile("NanoHTTPD-", "", new File(tempdir)); fstream = new FileOutputStream(file); } @Override public OutputStream open() { return fstream; } @Override public void delete() { safeClose(fstream); file.delete(); } @Override public String getName() { return file.getAbsolutePath(); } } /** * HTTP response. Return one of these from serve(). */ public static class Response { /** * HTTP status code after processing, e.g. "200 OK", HTTP_OK */ private IStatus status; /** * MIME type of content, e.g. "text/html" */ private String mimeType; /** * Data of the response, may be null. */ private InputStream data; /** * Headers for the HTTP response. Use addHeader() to add lines. */ private final Map<String, String> header = new ArrayMap<>(); /** * The request method that spawned this response. */ private Method requestMethod; /** * Use chunkedTransfer */ private boolean chunkedTransfer; /** * Default constructor: response = HTTP_OK, mime = MIME_HTML and your supplied message */ public Response(String msg) { this(Status.OK, MIME_HTML, msg); } /** * Basic constructor. */ public Response(IStatus status, String mimeType, InputStream data) { this.status = status; this.mimeType = mimeType; this.data = data; } /** * Convenience method that makes an InputStream out of given text. */ public Response(IStatus status, String mimeType, String txt) { this.status = status; this.mimeType = mimeType; try { this.data = txt != null ? new ByteArrayInputStream(txt.getBytes("UTF-8")) : null; } catch (java.io.UnsupportedEncodingException uee) { uee.printStackTrace(); } } /** * Adds given line to the header. */ public void addHeader(String name, String value) { header.put(name, value); } public String getHeader(String name) { return header.get(name); } /** * Sends given response to the socket. */ void send(OutputStream outputStream) { String mime = mimeType; SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT")); try { if (status == null) { throw new Error("sendResponse(): Status can't be null."); } PrintWriter pw = new PrintWriter(outputStream); pw.print("HTTP/1.1 " + status.getDescription() + " \r\n"); if (mime != null) { pw.print("Content-Type: " + mime + "\r\n"); } if (header == null || header.get("Date") == null) { pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n"); } if (header != null) { for (String key : header.keySet()) { String value = header.get(key); pw.print(key + ": " + value + "\r\n"); } } sendConnectionHeaderIfNotAlreadyPresent(pw, header); if (requestMethod != Method.HEAD && chunkedTransfer) { sendAsChunked(outputStream, pw); } else { int pending = data != null ? data.available() : 0; sendContentLengthHeaderIfNotAlreadyPresent(pw, header, pending); pw.print("\r\n"); pw.flush(); sendAsFixedLength(outputStream, pending); } outputStream.flush(); safeClose(data); } catch (IOException ioe) { // Couldn't write? No can do. } } void sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header, int size) { if (!headerAlreadySent(header, "content-length")) { pw.print("Content-Length: "+ size +"\r\n"); } } void sendConnectionHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header) { if (!headerAlreadySent(header, "connection")) { pw.print("Connection: keep-alive\r\n"); } } private boolean headerAlreadySent(Map<String, String> header, String name) { boolean alreadySent = false; for (String headerName : header.keySet()) { alreadySent |= headerName.equalsIgnoreCase(name); } return alreadySent; } private void sendAsChunked(OutputStream outputStream, PrintWriter pw) throws IOException { pw.print("Transfer-Encoding: chunked\r\n"); pw.print("\r\n"); pw.flush(); int BUFFER_SIZE = 16 * 1024; byte[] CRLF = "\r\n".getBytes(); byte[] buff = new byte[BUFFER_SIZE]; int read; while ((read = data.read(buff)) > 0) { outputStream.write(String.format("%x\r\n", read).getBytes()); outputStream.write(buff, 0, read); outputStream.write(CRLF); } outputStream.write("0\r\n\r\n".getBytes()); } private void sendAsFixedLength(OutputStream outputStream, int pending) throws IOException { if (requestMethod != Method.HEAD && data != null) { int BUFFER_SIZE = 16 * 1024; byte[] buff = new byte[BUFFER_SIZE]; while (pending > 0) { int read = data.read(buff, 0, ((pending > BUFFER_SIZE) ? BUFFER_SIZE : pending)); if (read <= 0) { break; } outputStream.write(buff, 0, read); pending -= read; } } } public IStatus getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public String getMimeType() { return mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public InputStream getData() { return data; } public void setData(InputStream data) { this.data = data; } public Method getRequestMethod() { return requestMethod; } public void setRequestMethod(Method requestMethod) { this.requestMethod = requestMethod; } public void setChunkedTransfer(boolean chunkedTransfer) { this.chunkedTransfer = chunkedTransfer; } public interface IStatus { int getRequestStatus(); String getDescription(); } /** * Some HTTP response status codes */ public enum Status implements IStatus { SWITCH_PROTOCOL(101, "Switching Protocols"), OK(200, "OK"), CREATED(201, "Created"), ACCEPTED(202, "Accepted"), NO_CONTENT(204, "No Content"), PARTIAL_CONTENT(206, "Partial Content"), REDIRECT(301, "Moved Permanently"), NOT_MODIFIED(304, "Not Modified"), BAD_REQUEST(400, "Bad Request"), UNAUTHORIZED(401, "Unauthorized"), FORBIDDEN(403, "Forbidden"), NOT_FOUND(404, "Not Found"), METHOD_NOT_ALLOWED(405, "Method Not Allowed"), RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"), INTERNAL_ERROR(500, "Internal Server Error"); private final int requestStatus; private final String description; Status(int requestStatus, String description) { this.requestStatus = requestStatus; this.description = description; } @Override public int getRequestStatus() { return this.requestStatus; } @Override public String getDescription() { return "" + this.requestStatus + " " + description; } } } public static final class ResponseException extends Exception { private final Response.Status status; public ResponseException(Response.Status status, String message) { super(message); this.status = status; } public ResponseException(Response.Status status, String message, Exception e) { super(message, e); this.status = status; } public Response.Status getStatus() { return status; } } /** * Default strategy for creating and cleaning up temporary files. */ private class DefaultTempFileManagerFactory implements TempFileManagerFactory { @Override public TempFileManager create() { return new DefaultTempFileManager(); } } /** * Handles one session, i.e. parses the HTTP request and returns the response. */ public interface IHTTPSession { void execute() throws IOException; Map<String, String> getParms(); Map<String, String> getHeaders(); /** * @return the path part of the URL. */ String getUri(); String getQueryParameterString(); Method getMethod(); InputStream getInputStream(); CookieHandler getCookies(); /** * Adds the files in the request body to the files map. * @arg files - map to modify */ void parseBody(Map<String, String> files) throws IOException, ResponseException; } protected class HTTPSession implements IHTTPSession { public static final int BUFSIZE = 8192; private final TempFileManager tempFileManager; private final OutputStream outputStream; private final PushbackInputStream inputStream; private int splitbyte; private int rlen; private String uri; private Method method; private Map<String, String> parms; private Map<String, String> headers; private CookieHandler cookies; private String queryParameterString; public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) { this.tempFileManager = tempFileManager; this.inputStream = new PushbackInputStream(inputStream, BUFSIZE); this.outputStream = outputStream; } public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) { this.tempFileManager = tempFileManager; this.inputStream = new PushbackInputStream(inputStream, BUFSIZE); this.outputStream = outputStream; String remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString(); headers = new ArrayMap<>(); headers.put("remote-addr", remoteIp); headers.put("http-client-ip", remoteIp); } @Override public void execute() throws IOException { try { // Read the first 8192 bytes. // The full header should fit in here. // Apache's default header limit is 8KB. // Do NOT assume that a single read will get the entire header at once! byte[] buf = new byte[BUFSIZE]; splitbyte = 0; rlen = 0; { int read = -1; try { read = inputStream.read(buf, 0, BUFSIZE); } catch (Exception e) { safeClose(inputStream); safeClose(outputStream); throw new SocketException("NanoHttpd Shutdown"); } if (read == -1) { // socket was been closed safeClose(inputStream); safeClose(outputStream); throw new SocketException("NanoHttpd Shutdown"); } while (read > 0) { rlen += read; splitbyte = findHeaderEnd(buf, rlen); if (splitbyte > 0) break; read = inputStream.read(buf, rlen, BUFSIZE - rlen); } } if (splitbyte < rlen) { inputStream.unread(buf, splitbyte, rlen - splitbyte); } parms = new ArrayMap<>(); if(null == headers) { headers = new ArrayMap<>(); } // Create a BufferedReader for parsing the header. BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, rlen))); // Decode the header into parms and header java properties Map<String, String> pre = new ArrayMap<>(); decodeHeader(hin, pre, parms, headers); method = Method.lookup(pre.get("method")); if (method == null) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error."); } uri = pre.get("uri"); cookies = new CookieHandler(headers); // Ok, now do the serve() Response r = serve(this); if (r == null) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response."); } else { cookies.unloadQueue(r); r.setRequestMethod(method); r.send(outputStream); } } catch (SocketException e) { // throw it out to close socket object (finalAccept) throw e; } catch (SocketTimeoutException ste) { throw ste; } catch (IOException ioe) { Response r = new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); r.send(outputStream); safeClose(outputStream); } catch (ResponseException re) { Response r = new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage()); r.send(outputStream); safeClose(outputStream); } finally { tempFileManager.clear(); } } @Override public void parseBody(Map<String, String> files) throws IOException, ResponseException { RandomAccessFile randomAccessFile = null; BufferedReader in = null; try { randomAccessFile = getTmpBucket(); long size; if (headers.containsKey("content-length")) { size = Integer.parseInt(headers.get("content-length")); } else if (splitbyte < rlen) { size = rlen - splitbyte; } else { size = 0; } // Now read all the body and write it to f byte[] buf = new byte[512]; while (rlen >= 0 && size > 0) { rlen = inputStream.read(buf, 0, (int)Math.min(size, 512)); size -= rlen; if (rlen > 0) { randomAccessFile.write(buf, 0, rlen); } } // Get the raw body as a byte [] ByteBuffer fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length()); randomAccessFile.seek(0); // Create a BufferedReader for easily reading it as string. InputStream bin = new FileInputStream(randomAccessFile.getFD()); in = new BufferedReader(new InputStreamReader(bin)); // If the method is POST, there may be parameters // in data section, too, read it: if (Method.POST.equals(method)) { String contentType = ""; String contentTypeHeader = headers.get("content-type"); StringTokenizer st = null; if (contentTypeHeader != null) { st = new StringTokenizer(contentTypeHeader, ",; "); if (st.hasMoreTokens()) { contentType = st.nextToken(); } } if ("multipart/form-data".equalsIgnoreCase(contentType)) { // Handle multipart/form-data if (!st.hasMoreTokens()) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html"); } String boundaryStartString = "boundary="; int boundaryContentStart = contentTypeHeader.indexOf(boundaryStartString) + boundaryStartString.length(); String boundary = contentTypeHeader.substring(boundaryContentStart, contentTypeHeader.length()); if (boundary.startsWith("\"") && boundary.endsWith("\"")) { boundary = boundary.substring(1, boundary.length() - 1); } decodeMultipartData(boundary, fbuf, in, parms, files); } else { String postLine = ""; StringBuilder postLineBuffer = new StringBuilder(); char pbuf[] = new char[512]; int read = in.read(pbuf); while (read >= 0 && !postLine.endsWith("\r\n")) { postLine = String.valueOf(pbuf, 0, read); postLineBuffer.append(postLine); read = in.read(pbuf); } postLine = postLineBuffer.toString().trim(); // Handle application/x-www-form-urlencoded if ("application/x-www-form-urlencoded".equalsIgnoreCase(contentType)) { decodeParms(postLine, parms); } else if (postLine.length() != 0) { // Special case for raw POST data => create a special files entry "postData" with raw content data files.put("postData", postLine); } } } else if (Method.PUT.equals(method)) { files.put("content", saveTmpFile(fbuf, 0, fbuf.limit())); } } finally { safeClose(randomAccessFile); safeClose(in); } } /** * Decodes the sent headers and loads the data into Key/value pairs */ private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, String> parms, Map<String, String> headers) throws ResponseException { try { // Read the request line String inLine = in.readLine(); if (inLine == null) { return; } StringTokenizer st = new StringTokenizer(inLine); if (!st.hasMoreTokens()) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html"); } pre.put("method", st.nextToken()); if (!st.hasMoreTokens()) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html"); } String uri = st.nextToken(); // Decode parameters from the URI int qmi = uri.indexOf('?'); if (qmi >= 0) { decodeParms(uri.substring(qmi + 1), parms); uri = decodePercent(uri.substring(0, qmi)); } else { uri = decodePercent(uri); } // If there's another token, it's protocol version, // followed by HTTP headers. Ignore version but parse headers. // NOTE: this now forces header names lowercase since they are // case insensitive and vary by client. if (st.hasMoreTokens()) { String line = in.readLine(); while (line != null && line.trim().length() > 0) { int p = line.indexOf(':'); if (p >= 0) headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim()); line = in.readLine(); } } pre.put("uri", uri); } catch (IOException ioe) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe); } } /** * Decodes the Multipart Body data and put it into Key/Value pairs. */ private void decodeMultipartData(String boundary, ByteBuffer fbuf, BufferedReader in, Map<String, String> parms, Map<String, String> files) throws ResponseException { try { int[] bpositions = getBoundaryPositions(fbuf, boundary.getBytes()); int boundarycount = 1; String mpline = in.readLine(); while (mpline != null) { if (!mpline.contains(boundary)) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html"); } boundarycount++; Map<String, String> item = new ArrayMap<>(); mpline = in.readLine(); while (mpline != null && mpline.trim().length() > 0) { int p = mpline.indexOf(':'); if (p != -1) { item.put(mpline.substring(0, p).trim().toLowerCase(Locale.US), mpline.substring(p + 1).trim()); } mpline = in.readLine(); } if (mpline != null) { String contentDisposition = item.get("content-disposition"); if (contentDisposition == null) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html"); } StringTokenizer st = new StringTokenizer(contentDisposition, ";"); Map<String, String> disposition = new ArrayMap<>(); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); int p = token.indexOf('='); if (p != -1) { disposition.put(token.substring(0, p).trim().toLowerCase(Locale.US), token.substring(p + 1).trim()); } } String pname = disposition.get("name"); pname = pname.substring(1, pname.length() - 1); String value = ""; if (item.get("content-type") == null) { StringBuilder tmp = new StringBuilder(); while (mpline != null && !mpline.contains(boundary)) { mpline = in.readLine(); if (mpline != null) { int d = mpline.indexOf(boundary); if (d == -1) { tmp.append(mpline); } else { tmp.append(mpline.substring(0, d - 2)); } } } value = tmp.toString(); } else { if (boundarycount > bpositions.length) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "Error processing request"); } int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]); String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4); files.put(pname, path); value = disposition.get("filename"); value = value.substring(1, value.length() - 1); do { mpline = in.readLine(); } while (mpline != null && !mpline.contains(boundary)); } parms.put(pname, value); } } } catch (IOException ioe) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe); } } /** * Find byte index separating header from body. It must be the last byte of the first two sequential new lines. */ private int findHeaderEnd(final byte[] buf, int rlen) { int splitbyte = 0; while (splitbyte + 3 < rlen) { if (buf[splitbyte] == '\r' && buf[splitbyte + 1] == '\n' && buf[splitbyte + 2] == '\r' && buf[splitbyte + 3] == '\n') { return splitbyte + 4; } splitbyte++; } return 0; } /** * Find the byte positions where multipart boundaries start. */ private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) { int matchcount = 0; int matchbyte = -1; List<Integer> matchbytes = new ArrayList<>(); for (int i = 0; i < b.limit(); i++) { if (b.get(i) == boundary[matchcount]) { if (matchcount == 0) matchbyte = i; matchcount++; if (matchcount == boundary.length) { matchbytes.add(matchbyte); matchcount = 0; matchbyte = -1; } } else { i -= matchcount; matchcount = 0; matchbyte = -1; } } int[] ret = new int[matchbytes.size()]; for (int i = 0; i < ret.length; i++) { ret[i] = matchbytes.get(i); } return ret; } /** * Retrieves the content of a sent file and saves it to a temporary file. The full path to the saved file is returned. */ private String saveTmpFile(ByteBuffer b, int offset, int len) { String path = ""; if (len > 0) { FileOutputStream fileOutputStream = null; try { TempFile tempFile = tempFileManager.createTempFile(); ByteBuffer src = b.duplicate(); fileOutputStream = new FileOutputStream(tempFile.getName()); FileChannel dest = fileOutputStream.getChannel(); src.position(offset).limit(offset + len); dest.write(src.slice()); path = tempFile.getName(); } catch (Exception e) { // Catch exception if any throw new Error(e); // we won't recover, so throw an error } finally { safeClose(fileOutputStream); } } return path; } private RandomAccessFile getTmpBucket() { try { TempFile tempFile = tempFileManager.createTempFile(); return new RandomAccessFile(tempFile.getName(), "rw"); } catch (Exception e) { throw new Error(e); // we won't recover, so throw an error } } /** * It returns the offset separating multipart file headers from the file's data. */ private int stripMultipartHeaders(ByteBuffer b, int offset) { int i; for (i = offset; i < b.limit(); i++) { if (b.get(i) == '\r' && b.get(++i) == '\n' && b.get(++i) == '\r' && b.get(++i) == '\n') { break; } } return i + 1; } /** * Decodes parameters in percent-encoded URI-format ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and * adds them to given Map. NOTE: this doesn't support multiple identical keys due to the simplicity of Map. */ private void decodeParms(String parms, Map<String, String> p) { if (parms == null) { queryParameterString = ""; return; } queryParameterString = parms; StringTokenizer st = new StringTokenizer(parms, "&"); while (st.hasMoreTokens()) { String e = st.nextToken(); int sep = e.indexOf('='); if (sep >= 0) { p.put(decodePercent(e.substring(0, sep)).trim(), decodePercent(e.substring(sep + 1))); } else { p.put(decodePercent(e).trim(), ""); } } } @Override public final Map<String, String> getParms() { return parms; } public String getQueryParameterString() { return queryParameterString; } @Override public final Map<String, String> getHeaders() { return headers; } @Override public final String getUri() { return uri; } @Override public final Method getMethod() { return method; } @Override public final InputStream getInputStream() { return inputStream; } @Override public CookieHandler getCookies() { return cookies; } } public static class Cookie { private final String n; private final String v; private final String e; public Cookie(String name, String value, String expires) { n = name; v = value; e = expires; } public Cookie(String name, String value) { this(name, value, 30); } public Cookie(String name, String value, int numDays) { n = name; v = value; e = getHTTPTime(numDays); } public String getHTTPHeader() { String fmt = "%s=%s; expires=%s"; return String.format(fmt, n, v, e); } public static String getHTTPTime(int days) { Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); calendar.add(Calendar.DAY_OF_MONTH, days); return dateFormat.format(calendar.getTime()); } } /** * Provides rudimentary support for cookies. * Doesn't support 'path', 'secure' nor 'httpOnly'. * Feel free to improve it and/or add unsupported features. * * @author LordFokas */ public class CookieHandler implements Iterable<String> { private final ArrayMap<String, String> cookies = new ArrayMap<>(); private final ArrayList<Cookie> queue = new ArrayList<>(); public CookieHandler(Map<String, String> httpHeaders) { String raw = httpHeaders.get("cookie"); if (raw != null) { String[] tokens = raw.split(";"); for (String token : tokens) { String[] data = token.trim().split("="); if (data.length == 2) { cookies.put(data[0], data[1]); } } } } @Override public Iterator<String> iterator() { return cookies.keySet().iterator(); } /** * Read a cookie from the HTTP Headers. * * @param name The cookie's name. * @return The cookie's value if it exists, null otherwise. */ public String read(String name) { return cookies.get(name); } /** * Sets a cookie. * * @param name The cookie's name. * @param value The cookie's value. * @param expires How many days until the cookie expires. */ public void set(String name, String value, int expires) { queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires))); } public void set(Cookie cookie) { queue.add(cookie); } /** * Set a cookie with an expiration date from a month ago, effectively deleting it on the client side. * * @param name The cookie name. */ public void delete(String name) { set(name, "-delete-", -30); } /** * Internally used by the webserver to add all queued cookies into the Response's HTTP Headers. * * @param response The Response object to which headers the queued cookies will be added. */ public void unloadQueue(Response response) { for (Cookie cookie : queue) { response.addHeader("Set-Cookie", cookie.getHTTPHeader()); } } } }
app/src/androidTest/java/de/test/antennapod/util/service/download/NanoHTTPD.java
package de.test.antennapod.util.service.download; import android.support.v4.util.ArrayMap; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.PushbackInputStream; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URLDecoder; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TimeZone; /** * A simple, tiny, nicely embeddable HTTP server in Java * <p/> * <p/> * NanoHTTPD * <p></p>Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen, 2010 by Konstantinos Togias</p> * <p/> * <p/> * <b>Features + limitations: </b> * <ul> * <p/> * <li>Only one Java file</li> * <li>Java 5 compatible</li> * <li>Released as open source, Modified BSD licence</li> * <li>No fixed config files, logging, authorization etc. (Implement yourself if you need them.)</li> * <li>Supports parameter parsing of GET and POST methods (+ rudimentary PUT support in 1.25)</li> * <li>Supports both dynamic content and file serving</li> * <li>Supports file upload (since version 1.2, 2010)</li> * <li>Supports partial content (streaming)</li> * <li>Supports ETags</li> * <li>Never caches anything</li> * <li>Doesn't limit bandwidth, request time or simultaneous connections</li> * <li>Default code serves files and shows all HTTP parameters and headers</li> * <li>File server supports directory listing, index.html and index.htm</li> * <li>File server supports partial content (streaming)</li> * <li>File server supports ETags</li> * <li>File server does the 301 redirection trick for directories without '/'</li> * <li>File server supports simple skipping for files (continue download)</li> * <li>File server serves also very long files without memory overhead</li> * <li>Contains a built-in list of most common mime types</li> * <li>All header names are converted lowercase so they don't vary between browsers/clients</li> * <p/> * </ul> * <p/> * <p/> * <b>How to use: </b> * <ul> * <p/> * <li>Subclass and implement serve() and embed to your own program</li> * <p/> * </ul> * <p/> * See the separate "LICENSE.md" file for the distribution license (Modified BSD licence) */ public abstract class NanoHTTPD { /** * Maximum time to wait on Socket.getInputStream().read() (in milliseconds) * This is required as the Keep-Alive HTTP connections would otherwise * block the socket reading thread forever (or as long the browser is open). */ private static final int SOCKET_READ_TIMEOUT = 5000; /** * Common mime type for dynamic content: plain text */ private static final String MIME_PLAINTEXT = "text/plain"; /** * Common mime type for dynamic content: html */ private static final String MIME_HTML = "text/html"; /** * Pseudo-Parameter to use to store the actual query string in the parameters map for later re-processing. */ private static final String QUERY_STRING_PARAMETER = "NanoHttpd.QUERY_STRING"; private final String hostname; private final int myPort; private ServerSocket myServerSocket; private final Set<Socket> openConnections = new HashSet<>(); private Thread myThread; /** * Pluggable strategy for asynchronously executing requests. */ private AsyncRunner asyncRunner; /** * Pluggable strategy for creating and cleaning up temporary files. */ private TempFileManagerFactory tempFileManagerFactory; /** * Constructs an HTTP server on given port. */ NanoHTTPD(int port) { this(null, port); } /** * Constructs an HTTP server on given hostname and port. */ private NanoHTTPD(String hostname, int port) { this.hostname = hostname; this.myPort = port; setTempFileManagerFactory(new DefaultTempFileManagerFactory()); setAsyncRunner(new DefaultAsyncRunner()); } private static final void safeClose(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { } } } private static final void safeClose(Socket closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { } } } private static final void safeClose(ServerSocket closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { } } } /** * Start the server. * * @throws IOException if the socket is in use. */ public void start() throws IOException { myServerSocket = new ServerSocket(); myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort)); myThread = new Thread(() -> { do { try { final Socket finalAccept = myServerSocket.accept(); registerConnection(finalAccept); finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT); final InputStream inputStream = finalAccept.getInputStream(); asyncRunner.exec(() -> { OutputStream outputStream = null; try { outputStream = finalAccept.getOutputStream(); TempFileManager tempFileManager = tempFileManagerFactory.create(); HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress()); while (!finalAccept.isClosed()) { session.execute(); } } catch (Exception e) { // When the socket is closed by the client, we throw our own SocketException // to break the "keep alive" loop above. if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) { e.printStackTrace(); } } finally { safeClose(outputStream); safeClose(inputStream); safeClose(finalAccept); unRegisterConnection(finalAccept); } }); } catch (IOException e) { } } while (!myServerSocket.isClosed()); }); myThread.setDaemon(true); myThread.setName("NanoHttpd Main Listener"); myThread.start(); } /** * Stop the server. */ public void stop() { try { safeClose(myServerSocket); closeAllConnections(); if (myThread != null) { myThread.join(); } } catch (Exception e) { e.printStackTrace(); } } /** * Registers that a new connection has been set up. * * @param socket the {@link Socket} for the connection. */ private synchronized void registerConnection(Socket socket) { openConnections.add(socket); } /** * Registers that a connection has been closed * * @param socket * the {@link Socket} for the connection. */ private synchronized void unRegisterConnection(Socket socket) { openConnections.remove(socket); } /** * Forcibly closes all connections that are open. */ private synchronized void closeAllConnections() { for (Socket socket : openConnections) { safeClose(socket); } } public final int getListeningPort() { return myServerSocket == null ? -1 : myServerSocket.getLocalPort(); } private boolean wasStarted() { return myServerSocket != null && myThread != null; } public final boolean isAlive() { return wasStarted() && !myServerSocket.isClosed() && myThread.isAlive(); } /** * Override this to customize the server. * <p/> * <p/> * (By default, this delegates to serveFile() and allows directory listing.) * * @param uri Percent-decoded URI without parameters, for example "/index.cgi" * @param method "GET", "POST" etc. * @param parms Parsed, percent decoded parameters from URI and, in case of POST, data. * @param headers Header entries, percent decoded * @return HTTP response, see class Response for details */ @Deprecated public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) { return new Response(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found"); } /** * Override this to customize the server. * <p/> * <p/> * (By default, this delegates to serveFile() and allows directory listing.) * * @param session The HTTP session * @return HTTP response, see class Response for details */ Response serve(IHTTPSession session) { Map<String, String> files = new ArrayMap<>(); Method method = session.getMethod(); if (Method.PUT.equals(method) || Method.POST.equals(method)) { try { session.parseBody(files); } catch (IOException ioe) { return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); } catch (ResponseException re) { return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage()); } } Map<String, String> parms = session.getParms(); parms.put(QUERY_STRING_PARAMETER, session.getQueryParameterString()); return serve(session.getUri(), method, session.getHeaders(), parms, files); } /** * Decode percent encoded <code>String</code> values. * * @param str the percent encoded <code>String</code> * @return expanded form of the input, for example "foo%20bar" becomes "foo bar" */ private String decodePercent(String str) { String decoded = null; try { decoded = URLDecoder.decode(str, "UTF8"); } catch (UnsupportedEncodingException ignored) { } return decoded; } /** * Decode parameters from a URL, handing the case where a single parameter name might have been * supplied several times, by return lists of values. In general these lists will contain a single * element. * * @param parms original <b>NanoHttpd</b> parameters values, as passed to the <code>serve()</code> method. * @return a map of <code>String</code> (parameter name) to <code>List&lt;String&gt;</code> (a list of the values supplied). */ protected Map<String, List<String>> decodeParameters(Map<String, String> parms) { return this.decodeParameters(parms.get(QUERY_STRING_PARAMETER)); } /** * Decode parameters from a URL, handing the case where a single parameter name might have been * supplied several times, by return lists of values. In general these lists will contain a single * element. * * @param queryString a query string pulled from the URL. * @return a map of <code>String</code> (parameter name) to <code>List&lt;String&gt;</code> (a list of the values supplied). */ private Map<String, List<String>> decodeParameters(String queryString) { Map<String, List<String>> parms = new ArrayMap<>(); if (queryString != null) { StringTokenizer st = new StringTokenizer(queryString, "&"); while (st.hasMoreTokens()) { String e = st.nextToken(); int sep = e.indexOf('='); String propertyName = (sep >= 0) ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim(); if (!parms.containsKey(propertyName)) { parms.put(propertyName, new ArrayList<>()); } String propertyValue = (sep >= 0) ? decodePercent(e.substring(sep + 1)) : null; if (propertyValue != null) { parms.get(propertyName).add(propertyValue); } } } return parms; } // ------------------------------------------------------------------------------- // // // Threading Strategy. // // ------------------------------------------------------------------------------- // /** * Pluggable strategy for asynchronously executing requests. * * @param asyncRunner new strategy for handling threads. */ private void setAsyncRunner(AsyncRunner asyncRunner) { this.asyncRunner = asyncRunner; } // ------------------------------------------------------------------------------- // // // Temp file handling strategy. // // ------------------------------------------------------------------------------- // /** * Pluggable strategy for creating and cleaning up temporary files. * * @param tempFileManagerFactory new strategy for handling temp files. */ private void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) { this.tempFileManagerFactory = tempFileManagerFactory; } /** * HTTP Request methods, with the ability to decode a <code>String</code> back to its enum value. */ public enum Method { GET, PUT, POST, DELETE, HEAD, OPTIONS; static Method lookup(String method) { for (Method m : Method.values()) { if (m.toString().equalsIgnoreCase(method)) { return m; } } return null; } } /** * Pluggable strategy for asynchronously executing requests. */ public interface AsyncRunner { void exec(Runnable code); } /** * Factory to create temp file managers. */ public interface TempFileManagerFactory { TempFileManager create(); } // ------------------------------------------------------------------------------- // /** * Temp file manager. * <p/> * <p>Temp file managers are created 1-to-1 with incoming requests, to create and cleanup * temporary files created as a result of handling the request.</p> */ public interface TempFileManager { TempFile createTempFile() throws Exception; void clear(); } /** * A temp file. * <p/> * <p>Temp files are responsible for managing the actual temporary storage and cleaning * themselves up when no longer needed.</p> */ public interface TempFile { OutputStream open(); void delete(); String getName(); } /** * Default threading strategy for NanoHttpd. * <p/> * <p>By default, the server spawns a new Thread for every incoming request. These are set * to <i>daemon</i> status, and named according to the request number. The name is * useful when profiling the application.</p> */ public static class DefaultAsyncRunner implements AsyncRunner { private long requestCount; @Override public void exec(Runnable code) { ++requestCount; Thread t = new Thread(code); t.setDaemon(true); t.setName("NanoHttpd Request Processor (#" + requestCount + ")"); t.start(); } } /** * Default strategy for creating and cleaning up temporary files. * <p/> * <p></p>This class stores its files in the standard location (that is, * wherever <code>java.io.tmpdir</code> points to). Files are added * to an internal list, and deleted when no longer needed (that is, * when <code>clear()</code> is invoked at the end of processing a * request).</p> */ public static class DefaultTempFileManager implements TempFileManager { private final String tmpdir; private final List<TempFile> tempFiles; public DefaultTempFileManager() { tmpdir = System.getProperty("java.io.tmpdir"); tempFiles = new ArrayList<>(); } @Override public TempFile createTempFile() throws Exception { DefaultTempFile tempFile = new DefaultTempFile(tmpdir); tempFiles.add(tempFile); return tempFile; } @Override public void clear() { for (TempFile file : tempFiles) { try { file.delete(); } catch (Exception ignored) { } } tempFiles.clear(); } } /** * Default strategy for creating and cleaning up temporary files. * <p/> * <p></p></[>By default, files are created by <code>File.createTempFile()</code> in * the directory specified.</p> */ public static class DefaultTempFile implements TempFile { private File file; private OutputStream fstream; public DefaultTempFile(String tempdir) throws IOException { file = File.createTempFile("NanoHTTPD-", "", new File(tempdir)); fstream = new FileOutputStream(file); } @Override public OutputStream open() { return fstream; } @Override public void delete() { safeClose(fstream); file.delete(); } @Override public String getName() { return file.getAbsolutePath(); } } /** * HTTP response. Return one of these from serve(). */ public static class Response { /** * HTTP status code after processing, e.g. "200 OK", HTTP_OK */ private IStatus status; /** * MIME type of content, e.g. "text/html" */ private String mimeType; /** * Data of the response, may be null. */ private InputStream data; /** * Headers for the HTTP response. Use addHeader() to add lines. */ private final Map<String, String> header = new ArrayMap<>(); /** * The request method that spawned this response. */ private Method requestMethod; /** * Use chunkedTransfer */ private boolean chunkedTransfer; /** * Default constructor: response = HTTP_OK, mime = MIME_HTML and your supplied message */ public Response(String msg) { this(Status.OK, MIME_HTML, msg); } /** * Basic constructor. */ public Response(IStatus status, String mimeType, InputStream data) { this.status = status; this.mimeType = mimeType; this.data = data; } /** * Convenience method that makes an InputStream out of given text. */ public Response(IStatus status, String mimeType, String txt) { this.status = status; this.mimeType = mimeType; try { this.data = txt != null ? new ByteArrayInputStream(txt.getBytes("UTF-8")) : null; } catch (java.io.UnsupportedEncodingException uee) { uee.printStackTrace(); } } /** * Adds given line to the header. */ public void addHeader(String name, String value) { header.put(name, value); } public String getHeader(String name) { return header.get(name); } /** * Sends given response to the socket. */ void send(OutputStream outputStream) { String mime = mimeType; SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT")); try { if (status == null) { throw new Error("sendResponse(): Status can't be null."); } PrintWriter pw = new PrintWriter(outputStream); pw.print("HTTP/1.1 " + status.getDescription() + " \r\n"); if (mime != null) { pw.print("Content-Type: " + mime + "\r\n"); } if (header == null || header.get("Date") == null) { pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n"); } if (header != null) { for (String key : header.keySet()) { String value = header.get(key); pw.print(key + ": " + value + "\r\n"); } } sendConnectionHeaderIfNotAlreadyPresent(pw, header); if (requestMethod != Method.HEAD && chunkedTransfer) { sendAsChunked(outputStream, pw); } else { int pending = data != null ? data.available() : 0; sendContentLengthHeaderIfNotAlreadyPresent(pw, header, pending); pw.print("\r\n"); pw.flush(); sendAsFixedLength(outputStream, pending); } outputStream.flush(); safeClose(data); } catch (IOException ioe) { // Couldn't write? No can do. } } void sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header, int size) { if (!headerAlreadySent(header, "content-length")) { pw.print("Content-Length: "+ size +"\r\n"); } } void sendConnectionHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header) { if (!headerAlreadySent(header, "connection")) { pw.print("Connection: keep-alive\r\n"); } } private boolean headerAlreadySent(Map<String, String> header, String name) { boolean alreadySent = false; for (String headerName : header.keySet()) { alreadySent |= headerName.equalsIgnoreCase(name); } return alreadySent; } private void sendAsChunked(OutputStream outputStream, PrintWriter pw) throws IOException { pw.print("Transfer-Encoding: chunked\r\n"); pw.print("\r\n"); pw.flush(); int BUFFER_SIZE = 16 * 1024; byte[] CRLF = "\r\n".getBytes(); byte[] buff = new byte[BUFFER_SIZE]; int read; while ((read = data.read(buff)) > 0) { outputStream.write(String.format("%x\r\n", read).getBytes()); outputStream.write(buff, 0, read); outputStream.write(CRLF); } outputStream.write("0\r\n\r\n".getBytes()); } private void sendAsFixedLength(OutputStream outputStream, int pending) throws IOException { if (requestMethod != Method.HEAD && data != null) { int BUFFER_SIZE = 16 * 1024; byte[] buff = new byte[BUFFER_SIZE]; while (pending > 0) { int read = data.read(buff, 0, ((pending > BUFFER_SIZE) ? BUFFER_SIZE : pending)); if (read <= 0) { break; } outputStream.write(buff, 0, read); pending -= read; } } } public IStatus getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public String getMimeType() { return mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public InputStream getData() { return data; } public void setData(InputStream data) { this.data = data; } public Method getRequestMethod() { return requestMethod; } public void setRequestMethod(Method requestMethod) { this.requestMethod = requestMethod; } public void setChunkedTransfer(boolean chunkedTransfer) { this.chunkedTransfer = chunkedTransfer; } public interface IStatus { int getRequestStatus(); String getDescription(); } /** * Some HTTP response status codes */ public enum Status implements IStatus { SWITCH_PROTOCOL(101, "Switching Protocols"), OK(200, "OK"), CREATED(201, "Created"), ACCEPTED(202, "Accepted"), NO_CONTENT(204, "No Content"), PARTIAL_CONTENT(206, "Partial Content"), REDIRECT(301, "Moved Permanently"), NOT_MODIFIED(304, "Not Modified"), BAD_REQUEST(400, "Bad Request"), UNAUTHORIZED(401, "Unauthorized"), FORBIDDEN(403, "Forbidden"), NOT_FOUND(404, "Not Found"), METHOD_NOT_ALLOWED(405, "Method Not Allowed"), RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"), INTERNAL_ERROR(500, "Internal Server Error"); private final int requestStatus; private final String description; Status(int requestStatus, String description) { this.requestStatus = requestStatus; this.description = description; } @Override public int getRequestStatus() { return this.requestStatus; } @Override public String getDescription() { return "" + this.requestStatus + " " + description; } } } public static final class ResponseException extends Exception { private final Response.Status status; public ResponseException(Response.Status status, String message) { super(message); this.status = status; } public ResponseException(Response.Status status, String message, Exception e) { super(message, e); this.status = status; } public Response.Status getStatus() { return status; } } /** * Default strategy for creating and cleaning up temporary files. */ private class DefaultTempFileManagerFactory implements TempFileManagerFactory { @Override public TempFileManager create() { return new DefaultTempFileManager(); } } /** * Handles one session, i.e. parses the HTTP request and returns the response. */ public interface IHTTPSession { void execute() throws IOException; Map<String, String> getParms(); Map<String, String> getHeaders(); /** * @return the path part of the URL. */ String getUri(); String getQueryParameterString(); Method getMethod(); InputStream getInputStream(); CookieHandler getCookies(); /** * Adds the files in the request body to the files map. * @arg files - map to modify */ void parseBody(Map<String, String> files) throws IOException, ResponseException; } protected class HTTPSession implements IHTTPSession { public static final int BUFSIZE = 8192; private final TempFileManager tempFileManager; private final OutputStream outputStream; private final PushbackInputStream inputStream; private int splitbyte; private int rlen; private String uri; private Method method; private Map<String, String> parms; private Map<String, String> headers; private CookieHandler cookies; private String queryParameterString; public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) { this.tempFileManager = tempFileManager; this.inputStream = new PushbackInputStream(inputStream, BUFSIZE); this.outputStream = outputStream; } public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) { this.tempFileManager = tempFileManager; this.inputStream = new PushbackInputStream(inputStream, BUFSIZE); this.outputStream = outputStream; String remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString(); headers = new ArrayMap<>(); headers.put("remote-addr", remoteIp); headers.put("http-client-ip", remoteIp); } @Override public void execute() throws IOException { try { // Read the first 8192 bytes. // The full header should fit in here. // Apache's default header limit is 8KB. // Do NOT assume that a single read will get the entire header at once! byte[] buf = new byte[BUFSIZE]; splitbyte = 0; rlen = 0; { int read = -1; try { read = inputStream.read(buf, 0, BUFSIZE); } catch (Exception e) { safeClose(inputStream); safeClose(outputStream); throw new SocketException("NanoHttpd Shutdown"); } if (read == -1) { // socket was been closed safeClose(inputStream); safeClose(outputStream); throw new SocketException("NanoHttpd Shutdown"); } while (read > 0) { rlen += read; splitbyte = findHeaderEnd(buf, rlen); if (splitbyte > 0) break; read = inputStream.read(buf, rlen, BUFSIZE - rlen); } } if (splitbyte < rlen) { inputStream.unread(buf, splitbyte, rlen - splitbyte); } parms = new ArrayMap<>(); if(null == headers) { headers = new ArrayMap<>(); } // Create a BufferedReader for parsing the header. BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, rlen))); // Decode the header into parms and header java properties Map<String, String> pre = new ArrayMap<>(); decodeHeader(hin, pre, parms, headers); method = Method.lookup(pre.get("method")); if (method == null) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error."); } uri = pre.get("uri"); cookies = new CookieHandler(headers); // Ok, now do the serve() Response r = serve(this); if (r == null) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response."); } else { cookies.unloadQueue(r); r.setRequestMethod(method); r.send(outputStream); } } catch (SocketException e) { // throw it out to close socket object (finalAccept) throw e; } catch (SocketTimeoutException ste) { throw ste; } catch (IOException ioe) { Response r = new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); r.send(outputStream); safeClose(outputStream); } catch (ResponseException re) { Response r = new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage()); r.send(outputStream); safeClose(outputStream); } finally { tempFileManager.clear(); } } @Override public void parseBody(Map<String, String> files) throws IOException, ResponseException { RandomAccessFile randomAccessFile = null; BufferedReader in = null; try { randomAccessFile = getTmpBucket(); long size; if (headers.containsKey("content-length")) { size = Integer.parseInt(headers.get("content-length")); } else if (splitbyte < rlen) { size = rlen - splitbyte; } else { size = 0; } // Now read all the body and write it to f byte[] buf = new byte[512]; while (rlen >= 0 && size > 0) { rlen = inputStream.read(buf, 0, (int)Math.min(size, 512)); size -= rlen; if (rlen > 0) { randomAccessFile.write(buf, 0, rlen); } } // Get the raw body as a byte [] ByteBuffer fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length()); randomAccessFile.seek(0); // Create a BufferedReader for easily reading it as string. InputStream bin = new FileInputStream(randomAccessFile.getFD()); in = new BufferedReader(new InputStreamReader(bin)); // If the method is POST, there may be parameters // in data section, too, read it: if (Method.POST.equals(method)) { String contentType = ""; String contentTypeHeader = headers.get("content-type"); StringTokenizer st = null; if (contentTypeHeader != null) { st = new StringTokenizer(contentTypeHeader, ",; "); if (st.hasMoreTokens()) { contentType = st.nextToken(); } } if ("multipart/form-data".equalsIgnoreCase(contentType)) { // Handle multipart/form-data if (!st.hasMoreTokens()) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html"); } String boundaryStartString = "boundary="; int boundaryContentStart = contentTypeHeader.indexOf(boundaryStartString) + boundaryStartString.length(); String boundary = contentTypeHeader.substring(boundaryContentStart, contentTypeHeader.length()); if (boundary.startsWith("\"") && boundary.endsWith("\"")) { boundary = boundary.substring(1, boundary.length() - 1); } decodeMultipartData(boundary, fbuf, in, parms, files); } else { String postLine = ""; StringBuilder postLineBuffer = new StringBuilder(); char pbuf[] = new char[512]; int read = in.read(pbuf); while (read >= 0 && !postLine.endsWith("\r\n")) { postLine = String.valueOf(pbuf, 0, read); postLineBuffer.append(postLine); read = in.read(pbuf); } postLine = postLineBuffer.toString().trim(); // Handle application/x-www-form-urlencoded if ("application/x-www-form-urlencoded".equalsIgnoreCase(contentType)) { decodeParms(postLine, parms); } else if (postLine.length() != 0) { // Special case for raw POST data => create a special files entry "postData" with raw content data files.put("postData", postLine); } } } else if (Method.PUT.equals(method)) { files.put("content", saveTmpFile(fbuf, 0, fbuf.limit())); } } finally { safeClose(randomAccessFile); safeClose(in); } } /** * Decodes the sent headers and loads the data into Key/value pairs */ private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, String> parms, Map<String, String> headers) throws ResponseException { try { // Read the request line String inLine = in.readLine(); if (inLine == null) { return; } StringTokenizer st = new StringTokenizer(inLine); if (!st.hasMoreTokens()) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html"); } pre.put("method", st.nextToken()); if (!st.hasMoreTokens()) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html"); } String uri = st.nextToken(); // Decode parameters from the URI int qmi = uri.indexOf('?'); if (qmi >= 0) { decodeParms(uri.substring(qmi + 1), parms); uri = decodePercent(uri.substring(0, qmi)); } else { uri = decodePercent(uri); } // If there's another token, it's protocol version, // followed by HTTP headers. Ignore version but parse headers. // NOTE: this now forces header names lowercase since they are // case insensitive and vary by client. if (st.hasMoreTokens()) { String line = in.readLine(); while (line != null && line.trim().length() > 0) { int p = line.indexOf(':'); if (p >= 0) headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim()); line = in.readLine(); } } pre.put("uri", uri); } catch (IOException ioe) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe); } } /** * Decodes the Multipart Body data and put it into Key/Value pairs. */ private void decodeMultipartData(String boundary, ByteBuffer fbuf, BufferedReader in, Map<String, String> parms, Map<String, String> files) throws ResponseException { try { int[] bpositions = getBoundaryPositions(fbuf, boundary.getBytes()); int boundarycount = 1; String mpline = in.readLine(); while (mpline != null) { if (!mpline.contains(boundary)) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html"); } boundarycount++; Map<String, String> item = new ArrayMap<>(); mpline = in.readLine(); while (mpline != null && mpline.trim().length() > 0) { int p = mpline.indexOf(':'); if (p != -1) { item.put(mpline.substring(0, p).trim().toLowerCase(Locale.US), mpline.substring(p + 1).trim()); } mpline = in.readLine(); } if (mpline != null) { String contentDisposition = item.get("content-disposition"); if (contentDisposition == null) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html"); } StringTokenizer st = new StringTokenizer(contentDisposition, ";"); Map<String, String> disposition = new ArrayMap<>(); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); int p = token.indexOf('='); if (p != -1) { disposition.put(token.substring(0, p).trim().toLowerCase(Locale.US), token.substring(p + 1).trim()); } } String pname = disposition.get("name"); pname = pname.substring(1, pname.length() - 1); String value = ""; if (item.get("content-type") == null) { StringBuilder tmp = new StringBuilder(); while (mpline != null && !mpline.contains(boundary)) { mpline = in.readLine(); if (mpline != null) { int d = mpline.indexOf(boundary); if (d == -1) { tmp.append(mpline); } else { tmp.append(mpline.substring(0, d - 2)); } } } value = tmp.toString(); } else { if (boundarycount > bpositions.length) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "Error processing request"); } int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]); String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4); files.put(pname, path); value = disposition.get("filename").substring(1, value.length() - 1); do { mpline = in.readLine(); } while (mpline != null && !mpline.contains(boundary)); } parms.put(pname, value); } } } catch (IOException ioe) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe); } } /** * Find byte index separating header from body. It must be the last byte of the first two sequential new lines. */ private int findHeaderEnd(final byte[] buf, int rlen) { int splitbyte = 0; while (splitbyte + 3 < rlen) { if (buf[splitbyte] == '\r' && buf[splitbyte + 1] == '\n' && buf[splitbyte + 2] == '\r' && buf[splitbyte + 3] == '\n') { return splitbyte + 4; } splitbyte++; } return 0; } /** * Find the byte positions where multipart boundaries start. */ private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) { int matchcount = 0; int matchbyte = -1; List<Integer> matchbytes = new ArrayList<>(); for (int i = 0; i < b.limit(); i++) { if (b.get(i) == boundary[matchcount]) { if (matchcount == 0) matchbyte = i; matchcount++; if (matchcount == boundary.length) { matchbytes.add(matchbyte); matchcount = 0; matchbyte = -1; } } else { i -= matchcount; matchcount = 0; matchbyte = -1; } } int[] ret = new int[matchbytes.size()]; for (int i = 0; i < ret.length; i++) { ret[i] = matchbytes.get(i); } return ret; } /** * Retrieves the content of a sent file and saves it to a temporary file. The full path to the saved file is returned. */ private String saveTmpFile(ByteBuffer b, int offset, int len) { String path = ""; if (len > 0) { FileOutputStream fileOutputStream = null; try { TempFile tempFile = tempFileManager.createTempFile(); ByteBuffer src = b.duplicate(); fileOutputStream = new FileOutputStream(tempFile.getName()); FileChannel dest = fileOutputStream.getChannel(); src.position(offset).limit(offset + len); dest.write(src.slice()); path = tempFile.getName(); } catch (Exception e) { // Catch exception if any throw new Error(e); // we won't recover, so throw an error } finally { safeClose(fileOutputStream); } } return path; } private RandomAccessFile getTmpBucket() { try { TempFile tempFile = tempFileManager.createTempFile(); return new RandomAccessFile(tempFile.getName(), "rw"); } catch (Exception e) { throw new Error(e); // we won't recover, so throw an error } } /** * It returns the offset separating multipart file headers from the file's data. */ private int stripMultipartHeaders(ByteBuffer b, int offset) { int i; for (i = offset; i < b.limit(); i++) { if (b.get(i) == '\r' && b.get(++i) == '\n' && b.get(++i) == '\r' && b.get(++i) == '\n') { break; } } return i + 1; } /** * Decodes parameters in percent-encoded URI-format ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and * adds them to given Map. NOTE: this doesn't support multiple identical keys due to the simplicity of Map. */ private void decodeParms(String parms, Map<String, String> p) { if (parms == null) { queryParameterString = ""; return; } queryParameterString = parms; StringTokenizer st = new StringTokenizer(parms, "&"); while (st.hasMoreTokens()) { String e = st.nextToken(); int sep = e.indexOf('='); if (sep >= 0) { p.put(decodePercent(e.substring(0, sep)).trim(), decodePercent(e.substring(sep + 1))); } else { p.put(decodePercent(e).trim(), ""); } } } @Override public final Map<String, String> getParms() { return parms; } public String getQueryParameterString() { return queryParameterString; } @Override public final Map<String, String> getHeaders() { return headers; } @Override public final String getUri() { return uri; } @Override public final Method getMethod() { return method; } @Override public final InputStream getInputStream() { return inputStream; } @Override public CookieHandler getCookies() { return cookies; } } public static class Cookie { private final String n; private final String v; private final String e; public Cookie(String name, String value, String expires) { n = name; v = value; e = expires; } public Cookie(String name, String value) { this(name, value, 30); } public Cookie(String name, String value, int numDays) { n = name; v = value; e = getHTTPTime(numDays); } public String getHTTPHeader() { String fmt = "%s=%s; expires=%s"; return String.format(fmt, n, v, e); } public static String getHTTPTime(int days) { Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); calendar.add(Calendar.DAY_OF_MONTH, days); return dateFormat.format(calendar.getTime()); } } /** * Provides rudimentary support for cookies. * Doesn't support 'path', 'secure' nor 'httpOnly'. * Feel free to improve it and/or add unsupported features. * * @author LordFokas */ public class CookieHandler implements Iterable<String> { private final ArrayMap<String, String> cookies = new ArrayMap<>(); private final ArrayList<Cookie> queue = new ArrayList<>(); public CookieHandler(Map<String, String> httpHeaders) { String raw = httpHeaders.get("cookie"); if (raw != null) { String[] tokens = raw.split(";"); for (String token : tokens) { String[] data = token.trim().split("="); if (data.length == 2) { cookies.put(data[0], data[1]); } } } } @Override public Iterator<String> iterator() { return cookies.keySet().iterator(); } /** * Read a cookie from the HTTP Headers. * * @param name The cookie's name. * @return The cookie's value if it exists, null otherwise. */ public String read(String name) { return cookies.get(name); } /** * Sets a cookie. * * @param name The cookie's name. * @param value The cookie's value. * @param expires How many days until the cookie expires. */ public void set(String name, String value, int expires) { queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires))); } public void set(Cookie cookie) { queue.add(cookie); } /** * Set a cookie with an expiration date from a month ago, effectively deleting it on the client side. * * @param name The cookie name. */ public void delete(String name) { set(name, "-delete-", -30); } /** * Internally used by the webserver to add all queued cookies into the Response's HTTP Headers. * * @param response The Response object to which headers the queued cookies will be added. */ public void unloadQueue(Response response) { for (Cookie cookie : queue) { response.addHeader("Set-Cookie", cookie.getHTTPHeader()); } } } }
Change back to old implementation
app/src/androidTest/java/de/test/antennapod/util/service/download/NanoHTTPD.java
Change back to old implementation
<ide><path>pp/src/androidTest/java/de/test/antennapod/util/service/download/NanoHTTPD.java <ide> int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]); <ide> String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4); <ide> files.put(pname, path); <del> value = disposition.get("filename").substring(1, value.length() - 1); <add> value = disposition.get("filename"); <add> value = value.substring(1, value.length() - 1); <ide> do { <ide> mpline = in.readLine(); <ide> } while (mpline != null && !mpline.contains(boundary));
JavaScript
mit
6d2b4a075d77a7078cda7f3ec24043db0080b29c
0
ankane/ahoy.js,ankane/ahoy.js
/* * Ahoy.js * Simple, powerful JavaScript analytics * https://github.com/ankane/ahoy.js * v0.2.1 * MIT License */ /*jslint browser: true, indent: 2, plusplus: true, vars: true */ (function (window) { "use strict"; var config = { urlPrefix: "", visitsUrl: "/ahoy/visits", eventsUrl: "/ahoy/events", cookieDomain: null, page: null, platform: "Web", useBeacon: false, startOnReady: true }; var ahoy = window.ahoy || window.Ahoy || {}; ahoy.configure = function (options) { for (var key in options) { if (options.hasOwnProperty(key)) { config[key] = options[key]; } } }; // legacy ahoy.configure(ahoy); var $ = window.jQuery || window.Zepto || window.$; var visitId, visitorId, track; var visitTtl = 4 * 60; // 4 hours var visitorTtl = 2 * 365 * 24 * 60; // 2 years var isReady = false; var queue = []; var canStringify = typeof(JSON) !== "undefined" && typeof(JSON.stringify) !== "undefined"; var eventQueue = []; function visitsUrl() { return config.urlPrefix + config.visitsUrl; } function eventsUrl() { return config.urlPrefix + config.eventsUrl; } function canTrackNow() { return (config.useBeacon || config.trackNow) && canStringify && typeof(window.navigator.sendBeacon) !== "undefined"; } // cookies // http://www.quirksmode.org/js/cookies.html function setCookie(name, value, ttl) { var expires = ""; var cookieDomain = ""; if (ttl) { var date = new Date(); date.setTime(date.getTime() + (ttl * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } var domain = config.cookieDomain || config.domain; if (domain) { cookieDomain = "; domain=" + domain; } document.cookie = name + "=" + escape(value) + expires + cookieDomain + "; path=/"; } function getCookie(name) { var i, c; var nameEQ = name + "="; var ca = document.cookie.split(';'); for (i = 0; i < ca.length; i++) { c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) === 0) { return unescape(c.substring(nameEQ.length, c.length)); } } return null; } function destroyCookie(name) { setCookie(name, "", -1); } function log(message) { if (getCookie("ahoy_debug")) { window.console.log(message); } } function setReady() { var callback; while (callback = queue.shift()) { callback(); } isReady = true; } function ready(callback) { if (isReady) { callback(); } else { queue.push(callback); } } // http://stackoverflow.com/a/2117523/1177228 function generateId() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } function saveEventQueue() { // TODO add stringify method for IE 7 and under if (canStringify) { setCookie("ahoy_events", JSON.stringify(eventQueue), 1); } } // from jquery-ujs function csrfToken() { return $("meta[name=csrf-token]").attr("content"); } function csrfParam() { return $("meta[name=csrf-param]").attr("content"); } function CSRFProtection(xhr) { var token = csrfToken(); if (token) xhr.setRequestHeader("X-CSRF-Token", token); } function sendRequest(url, data, success) { if (canStringify) { $.ajax({ type: "POST", url: url, data: JSON.stringify(data), contentType: "application/json; charset=utf-8", dataType: "json", beforeSend: CSRFProtection, success: success }); } } function eventData(event) { var data = { events: [event], visit_token: event.visit_token, visitor_token: event.visitor_token }; delete event.visit_token; delete event.visitor_token; return data; } function trackEvent(event) { ready( function () { sendRequest(eventsUrl(), eventData(event), function() { // remove from queue for (var i = 0; i < eventQueue.length; i++) { if (eventQueue[i].id == event.id) { eventQueue.splice(i, 1); break; } } saveEventQueue(); }); }); } function trackEventNow(event) { ready( function () { var data = eventData(event); var param = csrfParam(); var token = csrfToken(); if (param && token) data[param] = token; var payload = new Blob([JSON.stringify(data)], {type : "application/json; charset=utf-8"}); navigator.sendBeacon(eventsUrl(), payload); }); } function page() { return config.page || window.location.pathname; } function eventProperties(e) { var $target = $(e.currentTarget); return { tag: $target.get(0).tagName.toLowerCase(), id: $target.attr("id"), "class": $target.attr("class"), page: page(), section: $target.closest("*[data-section]").data("section") }; } function createVisit() { isReady = false; visitId = ahoy.getVisitId(); visitorId = ahoy.getVisitorId(); track = getCookie("ahoy_track"); if (visitId && visitorId && !track) { // TODO keep visit alive? log("Active visit"); setReady(); } else { if (track) { destroyCookie("ahoy_track"); } if (!visitId) { visitId = generateId(); setCookie("ahoy_visit", visitId, visitTtl); } // make sure cookies are enabled if (getCookie("ahoy_visit")) { log("Visit started"); if (!visitorId) { visitorId = generateId(); setCookie("ahoy_visitor", visitorId, visitorTtl); } var data = { visit_token: visitId, visitor_token: visitorId, platform: config.platform, landing_page: window.location.href, screen_width: window.screen.width, screen_height: window.screen.height }; // referrer if (document.referrer.length > 0) { data.referrer = document.referrer; } log(data); sendRequest(visitsUrl(), data, setReady); } else { log("Cookies disabled"); setReady(); } } } ahoy.getVisitId = ahoy.getVisitToken = function () { return getCookie("ahoy_visit"); }; ahoy.getVisitorId = ahoy.getVisitorToken = function () { return getCookie("ahoy_visitor"); }; ahoy.reset = function () { destroyCookie("ahoy_visit"); destroyCookie("ahoy_visitor"); destroyCookie("ahoy_events"); destroyCookie("ahoy_track"); return true; }; ahoy.debug = function (enabled) { if (enabled === false) { destroyCookie("ahoy_debug"); } else { setCookie("ahoy_debug", "t", 365 * 24 * 60); // 1 year } return true; }; ahoy.track = function (name, properties) { // generate unique id var event = { id: generateId(), name: name, properties: properties || {}, time: (new Date()).getTime() / 1000.0 }; // wait for createVisit to log document.addEventListener("DOMContentLoaded", function() { log(event); }); ready( function () { if (!ahoy.getVisitId()) { createVisit(); } event.visit_token = ahoy.getVisitId(); event.visitor_token = ahoy.getVisitorId(); if (canTrackNow()) { trackEventNow(event); } else { eventQueue.push(event); saveEventQueue(); // wait in case navigating to reduce duplicate events setTimeout( function () { trackEvent(event); }, 1000); } }); }; ahoy.trackView = function (additionalProperties) { var properties = { url: window.location.href, title: document.title, page: page() }; if (additionalProperties) { for(var propName in additionalProperties) { if (additionalProperties.hasOwnProperty(propName)) { properties[propName] = additionalProperties[propName]; } } } ahoy.track("$view", properties); }; ahoy.trackClicks = function () { var elements = document.querySelectorAll("a, button, input[type=submit]"); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('click', function (e) { var target = e.currentTarget; var properties = eventProperties(e); properties.text = properties.tag == "input" ? target.value : (target.textContent || target.innerText || target.innerHTML).replace(/[\s\r\n]+/g, " ")); properties.href = target.href; ahoy.track("$click", properties); }); } }; ahoy.trackSubmits = function () { var elements = document.querySelectorAll("form"); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener("submit", function(e) { var properties = eventProperties(e); ahoy.track("$submit", properties); }); } }; ahoy.trackChanges = function () { var elements = document.querySelectorAll("change", "input, textarea, select"); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener("change", function(e) { var properties = eventProperties(e); ahoy.track("$change", properties); }); } }; ahoy.trackAll = function() { ahoy.trackView(); ahoy.trackClicks(); ahoy.trackSubmits(); ahoy.trackChanges(); }; // push events from queue try { eventQueue = JSON.parse(getCookie("ahoy_events") || "[]"); } catch (e) { // do nothing } for (var i = 0; i < eventQueue.length; i++) { trackEvent(eventQueue[i]); } ahoy.start = function () { createVisit(); ahoy.start = function () {}; }; document.addEventListener("DOMContentLoaded", function() { if (config.startOnReady) { ahoy.start(); } }); window.ahoy = ahoy; }(window));
ahoy.js
/* * Ahoy.js * Simple, powerful JavaScript analytics * https://github.com/ankane/ahoy.js * v0.2.1 * MIT License */ /*jslint browser: true, indent: 2, plusplus: true, vars: true */ (function (window) { "use strict"; var config = { urlPrefix: "", visitsUrl: "/ahoy/visits", eventsUrl: "/ahoy/events", cookieDomain: null, page: null, platform: "Web", useBeacon: false, startOnReady: true }; var ahoy = window.ahoy || window.Ahoy || {}; ahoy.configure = function (options) { for (var key in options) { if (options.hasOwnProperty(key)) { config[key] = options[key]; } } }; // legacy ahoy.configure(ahoy); var $ = window.jQuery || window.Zepto || window.$; var visitId, visitorId, track; var visitTtl = 4 * 60; // 4 hours var visitorTtl = 2 * 365 * 24 * 60; // 2 years var isReady = false; var queue = []; var canStringify = typeof(JSON) !== "undefined" && typeof(JSON.stringify) !== "undefined"; var eventQueue = []; function visitsUrl() { return config.urlPrefix + config.visitsUrl; } function eventsUrl() { return config.urlPrefix + config.eventsUrl; } function canTrackNow() { return (config.useBeacon || config.trackNow) && canStringify && typeof(window.navigator.sendBeacon) !== "undefined"; } // cookies // http://www.quirksmode.org/js/cookies.html function setCookie(name, value, ttl) { var expires = ""; var cookieDomain = ""; if (ttl) { var date = new Date(); date.setTime(date.getTime() + (ttl * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } var domain = config.cookieDomain || config.domain; if (domain) { cookieDomain = "; domain=" + domain; } document.cookie = name + "=" + escape(value) + expires + cookieDomain + "; path=/"; } function getCookie(name) { var i, c; var nameEQ = name + "="; var ca = document.cookie.split(';'); for (i = 0; i < ca.length; i++) { c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) === 0) { return unescape(c.substring(nameEQ.length, c.length)); } } return null; } function destroyCookie(name) { setCookie(name, "", -1); } function log(message) { if (getCookie("ahoy_debug")) { window.console.log(message); } } function setReady() { var callback; while (callback = queue.shift()) { callback(); } isReady = true; } function ready(callback) { if (isReady) { callback(); } else { queue.push(callback); } } // http://stackoverflow.com/a/2117523/1177228 function generateId() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } function saveEventQueue() { // TODO add stringify method for IE 7 and under if (canStringify) { setCookie("ahoy_events", JSON.stringify(eventQueue), 1); } } // from jquery-ujs function csrfToken() { return $("meta[name=csrf-token]").attr("content"); } function csrfParam() { return $("meta[name=csrf-param]").attr("content"); } function CSRFProtection(xhr) { var token = csrfToken(); if (token) xhr.setRequestHeader("X-CSRF-Token", token); } function sendRequest(url, data, success) { if (canStringify) { $.ajax({ type: "POST", url: url, data: JSON.stringify(data), contentType: "application/json; charset=utf-8", dataType: "json", beforeSend: CSRFProtection, success: success }); } } function eventData(event) { var data = { events: [event], visit_token: event.visit_token, visitor_token: event.visitor_token }; delete event.visit_token; delete event.visitor_token; return data; } function trackEvent(event) { ready( function () { sendRequest(eventsUrl(), eventData(event), function() { // remove from queue for (var i = 0; i < eventQueue.length; i++) { if (eventQueue[i].id == event.id) { eventQueue.splice(i, 1); break; } } saveEventQueue(); }); }); } function trackEventNow(event) { ready( function () { var data = eventData(event); var param = csrfParam(); var token = csrfToken(); if (param && token) data[param] = token; var payload = new Blob([JSON.stringify(data)], {type : "application/json; charset=utf-8"}); navigator.sendBeacon(eventsUrl(), payload); }); } function page() { return config.page || window.location.pathname; } function eventProperties(e) { var $target = $(e.currentTarget); return { tag: $target.get(0).tagName.toLowerCase(), id: $target.attr("id"), "class": $target.attr("class"), page: page(), section: $target.closest("*[data-section]").data("section") }; } function createVisit() { isReady = false; visitId = ahoy.getVisitId(); visitorId = ahoy.getVisitorId(); track = getCookie("ahoy_track"); if (visitId && visitorId && !track) { // TODO keep visit alive? log("Active visit"); setReady(); } else { if (track) { destroyCookie("ahoy_track"); } if (!visitId) { visitId = generateId(); setCookie("ahoy_visit", visitId, visitTtl); } // make sure cookies are enabled if (getCookie("ahoy_visit")) { log("Visit started"); if (!visitorId) { visitorId = generateId(); setCookie("ahoy_visitor", visitorId, visitorTtl); } var data = { visit_token: visitId, visitor_token: visitorId, platform: config.platform, landing_page: window.location.href, screen_width: window.screen.width, screen_height: window.screen.height }; // referrer if (document.referrer.length > 0) { data.referrer = document.referrer; } log(data); sendRequest(visitsUrl(), data, setReady); } else { log("Cookies disabled"); setReady(); } } } ahoy.getVisitId = ahoy.getVisitToken = function () { return getCookie("ahoy_visit"); }; ahoy.getVisitorId = ahoy.getVisitorToken = function () { return getCookie("ahoy_visitor"); }; ahoy.reset = function () { destroyCookie("ahoy_visit"); destroyCookie("ahoy_visitor"); destroyCookie("ahoy_events"); destroyCookie("ahoy_track"); return true; }; ahoy.debug = function (enabled) { if (enabled === false) { destroyCookie("ahoy_debug"); } else { setCookie("ahoy_debug", "t", 365 * 24 * 60); // 1 year } return true; }; ahoy.track = function (name, properties) { // generate unique id var event = { id: generateId(), name: name, properties: properties || {}, time: (new Date()).getTime() / 1000.0 }; // wait for createVisit to log $( function () { log(event); }); ready( function () { if (!ahoy.getVisitId()) { createVisit(); } event.visit_token = ahoy.getVisitId(); event.visitor_token = ahoy.getVisitorId(); if (canTrackNow()) { trackEventNow(event); } else { eventQueue.push(event); saveEventQueue(); // wait in case navigating to reduce duplicate events setTimeout( function () { trackEvent(event); }, 1000); } }); }; ahoy.trackView = function (additionalProperties) { var properties = { url: window.location.href, title: document.title, page: page() }; if (additionalProperties) { for(var propName in additionalProperties) { if (additionalProperties.hasOwnProperty(propName)) { properties[propName] = additionalProperties[propName]; } } } ahoy.track("$view", properties); }; ahoy.trackClicks = function () { var elements = document.querySelectorAll("a, button, input[type=submit]"); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('click', function (e) { var target = e.currentTarget; var properties = eventProperties(e); properties.text = properties.tag == "input" ? target.value : (target.textContent || target.innerText || target.innerHTML).replace(/[\s\r\n]+/g, " ")); properties.href = target.href; ahoy.track("$click", properties); }); } }; ahoy.trackSubmits = function () { var elements = document.querySelectorAll("form"); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener("submit", function(e) { var properties = eventProperties(e); ahoy.track("$submit", properties); }); } }; ahoy.trackChanges = function () { var elements = document.querySelectorAll("change", "input, textarea, select"); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener("change", function(e) { var properties = eventProperties(e); ahoy.track("$change", properties); }); } }; ahoy.trackAll = function() { ahoy.trackView(); ahoy.trackClicks(); ahoy.trackSubmits(); ahoy.trackChanges(); }; // push events from queue try { eventQueue = JSON.parse(getCookie("ahoy_events") || "[]"); } catch (e) { // do nothing } for (var i = 0; i < eventQueue.length; i++) { trackEvent(eventQueue[i]); } ahoy.start = function () { createVisit(); ahoy.start = function () {}; }; $( function () { if (config.startOnReady) { ahoy.start(); } }); window.ahoy = ahoy; }(window));
Replace jQuery document ready function
ahoy.js
Replace jQuery document ready function
<ide><path>hoy.js <ide> }; <ide> <ide> // wait for createVisit to log <del> $( function () { <add> document.addEventListener("DOMContentLoaded", function() { <ide> log(event); <ide> }); <ide> <ide> ahoy.start = function () {}; <ide> }; <ide> <del> $( function () { <add> document.addEventListener("DOMContentLoaded", function() { <ide> if (config.startOnReady) { <ide> ahoy.start(); <ide> }
JavaScript
mit
8817c23110cc71dc1c69fcd924f735e335a2297a
0
mwmwmw/Mizzy
import DataProcess from "./DataProcess"; import { MIDI_AFTERTOUCH, MIDI_CHANNEL_PRESSURE, MIDI_CONTROL_CHANGE, MIDI_MESSAGE_EVENT, MIDI_NOTE_OFF, MIDI_NOTE_ON, MIDI_PITCHBEND, MIDI_PROGRAM_CHANGE, NOTE_OFF_EVENT, NOTE_ON_EVENT, CONTROLLER_EVENT, PITCHWHEEL_EVENT } from "./Constants"; export default class Generate { static NoteOn(noteNumber, velocity) { return new Uint8Array([MIDI_NOTE_ON, noteNumber, velocity]); } static NoteOff(noteNumber, velocity) { return new Uint8Array([MIDI_NOTE_OFF, noteNumber, velocity]); } static AfterTouch(noteNumber, value) { return new Uint8Array([MIDI_AFTERTOUCH, noteNumber, value]); } static CC(controller, value) { return new Uint8Array([MIDI_CONTROL_CHANGE, controller, value]); } static ProgramChange(instrument) { return new Uint8Array([MIDI_PROGRAM_CHANGE, instrument]); } static ChannelPressure(pressure) { return new Uint8Array([MIDI_CHANNEL_PRESSURE, pressure]); } static PitchBend(value) { var msb = 0, lsb = 0; return new Uint8Array([MIDI_PITCHBEND, msb, lsb]); } static MidiEvent (data, key) { const {MIDIMessageEvent} = window; const message = new MIDIMessageEvent(MIDI_MESSAGE_EVENT, {"data": data}) || {"data": data}; switch (data[0] & 0xF0) { case MIDI_NOTE_ON: return DataProcess.NoteEvent(message, key); case MIDI_NOTE_OFF: return DataProcess.NoteEvent(message, key); case MIDI_CONTROL_CHANGE: return DataProcess.CCEvent(message); case MIDI_PITCHBEND: return DataProcess.PitchWheelEvent(message); case MIDI_AFTERTOUCH: return DataProcess.MidiControlEvent(message, AFTERTOUCH_EVENT); case MIDI_PROGRAM_CHANGE: return DataProcess.MidiControlEvent(message, PROGRAM_CHANGE_EVENT); } } static NoteEvent(messageType, value, velocity = 127) { const {MIDIMessageEvent} = window; let data = null; switch (messageType) { case NOTE_ON_EVENT: data = Generate.NoteOn(value, velocity); break; case NOTE_OFF_EVENT: data = Generate.NoteOff(value, velocity); break; } const newMessage = new window.MIDIMessageEvent(MIDI_MESSAGE_EVENT, {"data": data}) || {"data": data}; return DataProcess.NoteEvent(newMessage, this.key); } static CCEvent(cc, value) { const {MIDIMessageEvent} = window; let data = Generate.CC(cc, value); const newMessage = new window.MIDIMessageEvent(MIDI_MESSAGE_EVENT, {"data": data}); return DataProcess.CCEvent(newMessage); } static PitchBendEvent(value) { const {MIDIMessageEvent} = window; let data = Generate.PitchBend(value); const newMessage = new window.MIDIMessageEvent(MIDI_MESSAGE_EVENT, {"data": data}); return DataProcess.CCEvent(newMessage); } }
src/Generate.js
import DataProcess from "./DataProcess"; import { MIDI_AFTERTOUCH, MIDI_CHANNEL_PRESSURE, MIDI_CONTROL_CHANGE, MIDI_MESSAGE_EVENT, MIDI_NOTE_OFF, MIDI_NOTE_ON, MIDI_PITCHBEND, MIDI_PROGRAM_CHANGE, NOTE_OFF_EVENT, NOTE_ON_EVENT, CONTROLLER_EVENT, PITCHWHEEL_EVENT } from "./Constants"; export default class Generate { static NoteOn(noteNumber, velocity) { return new Uint8Array([MIDI_NOTE_ON, noteNumber, velocity]); } static NoteOff(noteNumber, velocity) { return new Uint8Array([MIDI_NOTE_OFF, noteNumber, velocity]); } static AfterTouch(noteNumber, value) { return new Uint8Array([MIDI_AFTERTOUCH, noteNumber, value]); } static CC(controller, value) { return new Uint8Array([MIDI_CONTROL_CHANGE, controller, value]); } static ProgramChange(instrument) { return new Uint8Array([MIDI_PROGRAM_CHANGE, instrument]); } static ChannelPressure(pressure) { return new Uint8Array([MIDI_CHANNEL_PRESSURE, pressure]); } static PitchBend(value) { var msb = 0, lsb = 0; return new Uint8Array([MIDI_PITCHBEND, msb, lsb]); } static MidiEvent (data, key) { const {MIDIMessageEvent} = window; const message = new MIDIMessageEvent(MIDI_MESSAGE_EVENT, {"data": data}) || {"data": data}; switch (data[0] & 0xF0) { case MIDI_NOTE_ON: return DataProcess.NoteEvent(message, key); case MIDI_NOTE_OFF: return DataProcess.NoteEvent(message, key); case MIDI_CONTROL_CHANGE: return DataProcess.CCEvent(message); case MIDI_PITCHBEND: return DataProcess.PitchWheelEvent(message); case MIDI_AFTERTOUCH: return DataProcess.MidiControlEvent(message, AFTERTOUCH_EVENT); case MIDI_PROGRAM_CHANGE: return DataProcess.MidiControlEvent(message, PROGRAM_CHANGE_EVENT); } } static NoteEvent(messageType, value, velocity = 127) { const {MIDIMessageEvent} = window; let data = null; switch (messageType) { case NOTE_ON_EVENT: data = Generate.NoteOn(value, velocity); break; case NOTE_OFF_EVENT: data = Generate.NoteOff(value, velocity); break; } const newMessage = new MIDIMessageEvent(MIDI_MESSAGE_EVENT, {"data": data}) || {"data": data}; return DataProcess.NoteEvent(newMessage, this.key); } static CCEvent(cc, value) { const {MIDIMessageEvent} = window; let data = Generate.CC(cc, value); const newMessage = new MIDIMessageEvent(MIDI_MESSAGE_EVENT, {"data": data}); return DataProcess.CCEvent(newMessage); } static PitchBendEvent(value) { const {MIDIMessageEvent} = window; let data = Generate.PitchBend(value); const newMessage = new MIDIMessageEvent(MIDI_MESSAGE_EVENT, {"data": data}); return DataProcess.CCEvent(newMessage); } }
Access MIDIMessageEvent from window
src/Generate.js
Access MIDIMessageEvent from window
<ide><path>rc/Generate.js <ide> data = Generate.NoteOff(value, velocity); <ide> break; <ide> } <del> const newMessage = new MIDIMessageEvent(MIDI_MESSAGE_EVENT, {"data": data}) || {"data": data}; <add> const newMessage = new window.MIDIMessageEvent(MIDI_MESSAGE_EVENT, {"data": data}) || {"data": data}; <ide> return DataProcess.NoteEvent(newMessage, this.key); <ide> } <ide> <ide> static CCEvent(cc, value) { <ide> const {MIDIMessageEvent} = window; <ide> let data = Generate.CC(cc, value); <del> const newMessage = new MIDIMessageEvent(MIDI_MESSAGE_EVENT, {"data": data}); <add> const newMessage = new window.MIDIMessageEvent(MIDI_MESSAGE_EVENT, {"data": data}); <ide> return DataProcess.CCEvent(newMessage); <ide> } <ide> <ide> static PitchBendEvent(value) { <ide> const {MIDIMessageEvent} = window; <ide> let data = Generate.PitchBend(value); <del> const newMessage = new MIDIMessageEvent(MIDI_MESSAGE_EVENT, {"data": data}); <add> const newMessage = new window.MIDIMessageEvent(MIDI_MESSAGE_EVENT, {"data": data}); <ide> return DataProcess.CCEvent(newMessage); <ide> } <ide> }
Java
mit
ddf460f98afe320571dc12b3c8c2eace285538e0
0
gharris1727/Catan
package catan.common.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Created by greg on 3/12/16. * A Pseudo-random number generator that is reversible. * Based on the MessageDigest's SHA implementation. */ public class ReversiblePRNG { private long seed; private final MessageDigest hash; public ReversiblePRNG(long seed) { this.seed = seed; try { hash = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Error(e); } } public void next() { seed++; } public void prev() { seed--; } private byte[] getBytes() { byte[] arr = new byte[8]; for (int i = 0; i < 8; i++) arr[i] = (byte) (seed >> 8*i); hash.reset(); return hash.digest(arr); } private int getInt() { byte[] bytes = getBytes(); int out = 0; for (int i = 0; i < 4; i++) { out = out << 8; out |= bytes[i]; } return out & 0x7fffffff; } public int getInt(int limit) { return getInt() % limit; } public int nextInt(int limit) { int next = getInt(limit); next(); return next; } public int prevInt(int limit) { prev(); return getInt(limit); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ReversiblePRNG)) return false; ReversiblePRNG that = (ReversiblePRNG) o; return seed == that.seed; } @Override public int hashCode() { return (int) (seed ^ (seed >>> 32)); } @Override public String toString() { return "ReversiblePRNG(" + seed + ")"; } }
catan/src/main/java/catan/common/util/ReversiblePRNG.java
package catan.common.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Created by greg on 3/12/16. * A Pseudo-random number generator that is reversible. * Based on the MessageDigest's SHA implementation. */ public class ReversiblePRNG { private long seed; private static MessageDigest hash; static { try { hash = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { hash = null; } } public ReversiblePRNG(long seed) { this.seed = seed; } public void next() { seed++; } public void prev() { seed--; } private byte[] getBytes() { byte[] arr = new byte[8]; for (int i = 0; i < 8; i++) arr[i] = (byte) (seed >> 8*i); hash.reset(); return hash.digest(arr); } private int getInt() { byte[] bytes = getBytes(); int out = 0; for (int i = 0; i < 4; i++) { out = out << 8; out |= bytes[i]; } return out & 0x7fffffff; } public int getInt(int limit) { return getInt() % limit; } public int nextInt(int limit) { int next = getInt(limit); next(); return next; } public int prevInt(int limit) { prev(); return getInt(limit); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ReversiblePRNG)) return false; ReversiblePRNG that = (ReversiblePRNG) o; return seed == that.seed; } @Override public int hashCode() { return (int) (seed ^ (seed >>> 32)); } @Override public String toString() { return "ReversiblePRNG(" + seed + ")"; } }
Fixed the dice roll race condition bug.
catan/src/main/java/catan/common/util/ReversiblePRNG.java
Fixed the dice roll race condition bug.
<ide><path>atan/src/main/java/catan/common/util/ReversiblePRNG.java <ide> public class ReversiblePRNG { <ide> <ide> private long seed; <del> private static MessageDigest hash; <add> private final MessageDigest hash; <ide> <del> static { <add> public ReversiblePRNG(long seed) { <add> this.seed = seed; <ide> try { <ide> hash = MessageDigest.getInstance("SHA"); <ide> } catch (NoSuchAlgorithmException e) { <del> hash = null; <add> throw new Error(e); <ide> } <del> } <del> <del> public ReversiblePRNG(long seed) { <del> this.seed = seed; <ide> } <ide> <ide> public void next() {
Java
mit
2a21473a31cbd4ecd498b9dac4d9a534d7b4fed8
0
mak326428/EnderAmmunition
package enderamm.item; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import enderamm.network.PacketRenderDebug; import enderamm.network.PacketSpawnParticle; import net.minecraft.block.Block; import net.minecraft.block.BlockCactus; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemSeeds; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.IPlantable; import net.minecraftforge.common.MinecraftForge; import java.awt.*; import java.util.List; import java.util.Map; /** * Created with IntelliJ IDEA. * User: Maxim * Date: 21.07.14 * Time: 19:11 * To change this template use File | Settings | File Templates. */ public class ItemGrowthAccelerator extends ItemBasicRF { public ItemGrowthAccelerator() { super(1000000, 100000, "Growth Accelerator", "enderamm:growth_booster"); FMLCommonHandler.instance().bus().register(this); MinecraftForge.EVENT_BUS.register(this); } @Override public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float argU1, float argU2, float argU3) { if (!world.isRemote && draw(stack, 25000)) { Block blck = world.getBlock(x, y, z); for (int i = 0; i < 400; i++) blck.updateTick(world, x, y, z, itemRand); for (int i1 = 0; i1 < 25; ++i1) { double d0 = itemRand.nextGaussian() * 0.02D; double d1 = itemRand.nextGaussian() * 0.02D; double d2 = itemRand.nextGaussian() * 0.02D; PacketSpawnParticle.issue("happyVillager", (double) ((float) x + itemRand.nextFloat()), (double) y + (double) itemRand.nextFloat() * blck.getBlockBoundsMaxY(), (double) ((float) z + itemRand.nextFloat()), d0, d1, d2, world); } } player.swingItem(); return false; } }
java/enderamm/item/ItemGrowthAccelerator.java
package enderamm.item; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import enderamm.network.PacketRenderDebug; import enderamm.network.PacketSpawnParticle; import net.minecraft.block.Block; import net.minecraft.block.BlockCactus; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemSeeds; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.IPlantable; import net.minecraftforge.common.MinecraftForge; import java.awt.*; import java.util.List; import java.util.Map; /** * Created with IntelliJ IDEA. * User: Maxim * Date: 21.07.14 * Time: 19:11 * To change this template use File | Settings | File Templates. */ public class ItemGrowthAccelerator extends ItemBasicRF { public static Map<Location, Integer> accelerateQueue = Maps.newHashMap(); public static class Location { public int dimID, x, y, z; } @SubscribeEvent public void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.END) { for (Location loc : accelerateQueue.keySet()) { World world = DimensionManager.getWorld(loc.dimID); Block blck = world.getBlock(loc.x, loc.y, loc.z); if (blck != null && blck != Blocks.air) { for (int i = 0; i < 5; i++) blck.updateTick(world, loc.x, loc.y, loc.z, itemRand); for (int i1 = 0; i1 < 10; ++i1) { double d0 = itemRand.nextGaussian() * 0.02D; double d1 = itemRand.nextGaussian() * 0.02D; double d2 = itemRand.nextGaussian() * 0.02D; PacketSpawnParticle.issue("happyVillager", (double) ((float) loc.x + itemRand.nextFloat()), (double) loc.y + (double) itemRand.nextFloat() * blck.getBlockBoundsMaxY(), (double) ((float) loc.z + itemRand.nextFloat()), d0, d1, d2, world); } } } Map<Location, Integer> newQ = Maps.newHashMap(); for (Map.Entry<Location, Integer> l : accelerateQueue.entrySet()) { if (l.getValue() - 1 > 0) newQ.put(l.getKey(), l.getValue() - 1); } accelerateQueue.clear(); accelerateQueue = newQ; } } public ItemGrowthAccelerator() { super(1000000, 100000, "Growth Accelerator", "enderamm:growth_booster"); FMLCommonHandler.instance().bus().register(this); MinecraftForge.EVENT_BUS.register(this); } @Override public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float argU1, float argU2, float argU3) { if (!world.isRemote && draw(stack, 25000)) { Location loc = new Location(); loc.dimID = world.provider.dimensionId; loc.x = x; loc.y = y; loc.z = z; accelerateQueue.put(loc, 100); } player.swingItem(); return false; } }
Actually make it easier
java/enderamm/item/ItemGrowthAccelerator.java
Actually make it easier
<ide><path>ava/enderamm/item/ItemGrowthAccelerator.java <ide> */ <ide> public class ItemGrowthAccelerator extends ItemBasicRF { <ide> <del> public static Map<Location, Integer> accelerateQueue = Maps.newHashMap(); <del> <del> public static class Location { <del> public int dimID, x, y, z; <del> } <del> <del> @SubscribeEvent <del> public void onServerTick(TickEvent.ServerTickEvent event) { <del> if (event.phase == TickEvent.Phase.END) { <del> for (Location loc : accelerateQueue.keySet()) { <del> World world = DimensionManager.getWorld(loc.dimID); <del> Block blck = world.getBlock(loc.x, loc.y, loc.z); <del> if (blck != null && blck != Blocks.air) { <del> for (int i = 0; i < 5; i++) <del> blck.updateTick(world, loc.x, loc.y, loc.z, itemRand); <del> for (int i1 = 0; i1 < 10; ++i1) { <del> double d0 = itemRand.nextGaussian() * 0.02D; <del> double d1 = itemRand.nextGaussian() * 0.02D; <del> double d2 = itemRand.nextGaussian() * 0.02D; <del> PacketSpawnParticle.issue("happyVillager", (double) ((float) loc.x + itemRand.nextFloat()), (double) loc.y + (double) itemRand.nextFloat() * blck.getBlockBoundsMaxY(), (double) ((float) loc.z + itemRand.nextFloat()), d0, d1, d2, world); <del> } <del> } <del> } <del> Map<Location, Integer> newQ = Maps.newHashMap(); <del> for (Map.Entry<Location, Integer> l : accelerateQueue.entrySet()) { <del> if (l.getValue() - 1 > 0) <del> newQ.put(l.getKey(), l.getValue() - 1); <del> } <del> accelerateQueue.clear(); <del> accelerateQueue = newQ; <del> } <del> } <del> <ide> public ItemGrowthAccelerator() { <ide> super(1000000, 100000, "Growth Accelerator", "enderamm:growth_booster"); <ide> FMLCommonHandler.instance().bus().register(this); <ide> @Override <ide> public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float argU1, float argU2, float argU3) { <ide> if (!world.isRemote && draw(stack, 25000)) { <del> Location loc = new Location(); <del> loc.dimID = world.provider.dimensionId; <del> loc.x = x; <del> loc.y = y; <del> loc.z = z; <del> accelerateQueue.put(loc, 100); <add> Block blck = world.getBlock(x, y, z); <add> for (int i = 0; i < 400; i++) <add> blck.updateTick(world, x, y, z, itemRand); <add> for (int i1 = 0; i1 < 25; ++i1) { <add> double d0 = itemRand.nextGaussian() * 0.02D; <add> double d1 = itemRand.nextGaussian() * 0.02D; <add> double d2 = itemRand.nextGaussian() * 0.02D; <add> PacketSpawnParticle.issue("happyVillager", (double) ((float) x + itemRand.nextFloat()), (double) y + (double) itemRand.nextFloat() * blck.getBlockBoundsMaxY(), (double) ((float) z + itemRand.nextFloat()), d0, d1, d2, world); <add> } <ide> } <ide> player.swingItem(); <ide> return false;
Java
apache-2.0
8ae61dcfa21374b4b98aec926d43adb01ad811fe
0
MoraisIgor/SlidingDrawer
/* * Copyright 2014 Igor Morais * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package hollowsoft.slidingdrawer; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Build; import android.os.SystemClock; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.VelocityTracker; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; /** * <p> SlidingDrawer hides content out of the screen and allows the user to drag a handle * to bring the content on screen. SlidingDrawer can be used vertically or horizontally. </p> * * <p> A special widget composed of two children views: the handle, that the users drags, * and the content, attached to the handle and dragged with it. </p> * * <p> SlidingDrawer should be used as an overlay inside layouts. This means SlidingDrawer * should only be used inside of a FrameLayout or a RelativeLayout for instance. </p> * * <p> The size of the SlidingDrawer defines how much space the content will occupy once slid * out so SlidingDrawer should usually use match_parent for both its dimensions. </p> * * <p> Inside an XML layout, SlidingDrawer must define the id of the handle and of the * content: </p> * * <pre class="prettyprint"> * &lt;hollowsoft.slidingdrawer.SlidingDrawer * android:id="@+id/drawer" * android:layout_width="match_parent" * android:layout_height="match_parent" * android:handle="@+id/handle" * android:content="@+id/content"&gt; * * &lt;ImageView * android:id="@id/handle" * android:layout_width="88dip" * android:layout_height="44dip"/&gt; * * &lt;GridView * android:id="@id/content" * android:layout_width="match_parent" * android:layout_height="match_parent"/&gt; * * &lt;/hollowsoft.slidingdrawer.SlidingDrawer&gt; * </pre> * * @author Igor Morais */ public class SlidingDrawer extends ViewGroup { private static final int TAP_THRESHOLD = 6; private static final float MAX_TAP_VELOCITY = 100.0f; private static final float MAX_MINOR_VELOCITY = 150.0f; private static final float MAX_MAJOR_VELOCITY = 200.0f; private static final float MAX_ACCELERATION = 2000.0f; private static final int VELOCITY_UNITS = 1000; private static final int ANIMATION_FRAME_DURATION = 1000 / 60; private static final int DRAWER_EXPANDED = 501; private static final int DRAWER_COLLAPSED = 502; private static final int ORIENTATION_VERTICAL = 1; private int tapThreshold; private int maxTapVelocity; private int maxMinorVelocity; private int maxMajorVelocity; private int maxAcceleration; private int velocityUnits; private float animationAcceleration; private float animationVelocity; private float animationPosition; private long animationLastTime; private int touchDelta; private VelocityTracker velocityTracker; private final Rect rectFrame = new Rect(); private final Rect rectInvalidate = new Rect(); private boolean tracking; private boolean animating; private boolean locked; private boolean expanded; private int handleWidth; private int handleHeight; /** * Styleable. */ private boolean animateOnClick; private boolean allowSingleTap; private int topOffset; private int bottomOffset; private boolean vertical; private int handleId; private int contentId; private View viewHandle; private View viewContent; private OnDrawerOpenListener onDrawerOpenListener; private OnDrawerCloseListener onDrawerCloseListener; private OnDrawerScrollListener onDrawerScrollListener; /** * Creates a new SlidingDrawer from a specified set of attributes defined in XML. * * @param context The applications environment. * @param attributeSet The attributes defined in XML. */ public SlidingDrawer(final Context context, final AttributeSet attributeSet) { this(context, attributeSet, 0); } /** * Creates a new SlidingDrawer from a specified set of attributes defined in XML. * * @param context The applications environment. * @param attributeSet The attributes defined in XML. * @param defStyleAttr An attribute in the current theme that contains a reference * to a style resource that supplies default values for the view. * Can be 0 to not look for defaults. */ public SlidingDrawer(final Context context, final AttributeSet attributeSet, final int defStyleAttr) { super(context, attributeSet, defStyleAttr); loadStyleable(context, attributeSet, defStyleAttr, 0); } /** * Creates a new SlidingDrawer from a specified set of attributes defined in XML. * * @param context The applications environment. * @param attributeSet The attributes defined in XML. * @param defStyleAttr An attribute in the current theme that contains a reference * to a style resource that supplies default values for the view. * Can be 0 to not look for defaults. * @param defStyleRes A resource identifier of a style resource that supplies * default values for the view, used only if defStyleAttr is 0 * or can not be found in the theme. Can be 0 to not look for defaults. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public SlidingDrawer(final Context context, final AttributeSet attributeSet, final int defStyleAttr, final int defStyleRes) { super(context, attributeSet, defStyleAttr, defStyleRes); loadStyleable(context, attributeSet, defStyleAttr, defStyleRes); } private void loadStyleable(final Context context, final AttributeSet attributeSet, final int defStyleAttr, final int defStyleRes) { final TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.SlidingDrawer, defStyleAttr, defStyleRes); animateOnClick = typedArray.getBoolean(R.styleable.SlidingDrawer_animateOnClick, true); allowSingleTap = typedArray.getBoolean(R.styleable.SlidingDrawer_allowSingleTap, true); topOffset = (int) typedArray.getDimension(R.styleable.SlidingDrawer_topOffset, 0.0f); bottomOffset = (int) typedArray.getDimension(R.styleable.SlidingDrawer_bottomOffset, 0.0f); vertical = typedArray.getInt(R.styleable.SlidingDrawer_android_orientation, ORIENTATION_VERTICAL) == ORIENTATION_VERTICAL; handleId = typedArray.getResourceId(R.styleable.SlidingDrawer_handle, 0); if (handleId == 0) { throw new IllegalArgumentException("The handle attribute is required and must refer to a valid child."); } contentId = typedArray.getResourceId(R.styleable.SlidingDrawer_content, 0); if (contentId == 0) { throw new IllegalArgumentException("The content attribute is required and must refer to a valid child."); } if (handleId == contentId) { throw new IllegalArgumentException("The content and handle attributes must refer to different children."); } typedArray.recycle(); final float density = getResources().getDisplayMetrics().density; tapThreshold = (int) (TAP_THRESHOLD * density + 0.5f); maxTapVelocity = (int) (MAX_TAP_VELOCITY * density + 0.5f); maxMinorVelocity = (int) (MAX_MINOR_VELOCITY * density + 0.5f); maxMajorVelocity = (int) (MAX_MAJOR_VELOCITY * density + 0.5f); maxAcceleration = (int) (MAX_ACCELERATION * density + 0.5f); velocityUnits = (int) (VELOCITY_UNITS * density + 0.5f); } @Override protected void onFinishInflate() { super.onFinishInflate(); viewHandle = findViewById(handleId); if (viewHandle == null) { throw new IllegalArgumentException("The handle attribute is must refer to an existing child."); } viewHandle.setOnClickListener(new DrawerToggle()); viewContent = findViewById(contentId); if (viewContent == null) { throw new IllegalArgumentException("The content attribute is must refer to an existing child."); } viewContent.setVisibility(View.GONE); } @Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); final int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); final int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) { throw new IllegalStateException("The Drawer cannot have unspecified dimensions."); } measureChild(viewHandle, widthMeasureSpec, heightMeasureSpec); if (vertical) { final int height = heightSpecSize - viewHandle.getMeasuredHeight() - topOffset; viewContent.measure(MeasureSpec.makeMeasureSpec(widthSpecSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); } else { final int width = widthSpecSize - viewHandle.getMeasuredWidth() - topOffset; viewContent.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSpecSize, MeasureSpec.EXACTLY)); } setMeasuredDimension(widthSpecSize, heightSpecSize); } @Override protected void onLayout(final boolean changed, final int left, final int top, final int right, final int bottom) { if (!tracking) { final int width = right - left; final int height = bottom - top; int childLeft; int childTop; int childWidth = viewHandle.getMeasuredWidth(); int childHeight = viewHandle.getMeasuredHeight(); if (vertical) { childLeft = (width - childWidth) / 2; childTop = expanded ? topOffset : height - childHeight + bottomOffset; viewContent.layout(0, topOffset + childHeight, viewContent.getMeasuredWidth(), topOffset + childHeight + viewContent.getMeasuredHeight()); } else { childLeft = expanded ? topOffset : width - childWidth + bottomOffset; childTop = (height - childHeight) / 2; viewContent.layout(topOffset + childWidth, 0, topOffset + childWidth + viewContent.getMeasuredWidth(), viewContent.getMeasuredHeight()); } viewHandle.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); handleWidth = viewHandle.getWidth(); handleHeight = viewHandle.getHeight(); } } @Override protected void dispatchDraw(@NonNull final Canvas canvas) { final long drawingTime = getDrawingTime(); drawChild(canvas, viewHandle, drawingTime); if (tracking || animating) { final Bitmap bitmap = viewContent.getDrawingCache(); if (bitmap == null) { canvas.save(); canvas.translate(vertical ? 0 : viewHandle.getLeft() - topOffset, vertical ? viewHandle.getTop() - topOffset : 0); drawChild(canvas, viewContent, drawingTime); canvas.restore(); } else { if (vertical) { canvas.drawBitmap(bitmap, 0, viewHandle.getBottom(), null); } else { canvas.drawBitmap(bitmap, viewHandle.getRight(), 0, null); } } } else if (expanded) { drawChild(canvas, viewContent, drawingTime); } } @Override public boolean onInterceptTouchEvent(final MotionEvent event) { if (locked) { return false; } final int action = event.getAction(); final float x = event.getX(); final float y = event.getY(); viewHandle.getHitRect(rectFrame); if (!tracking && !rectFrame.contains((int) x, (int) y)) { return false; } if (action == MotionEvent.ACTION_DOWN) { tracking = true; viewHandle.setPressed(true); prepareContent(); if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollStarted(); } if (vertical) { final int top = viewHandle.getTop(); touchDelta = (int) y - top; prepareTracking(top); } else { final int left = viewHandle.getLeft(); touchDelta = (int) x - left; prepareTracking(left); } velocityTracker.addMovement(event); } return true; } @Override public boolean onTouchEvent(@NonNull final MotionEvent event) { if (locked) { return true; } if (tracking) { velocityTracker.addMovement(event); final int action = event.getAction(); switch (action) { case MotionEvent.ACTION_MOVE: moveHandle((int) (vertical ? event.getY() : event.getX()) - touchDelta); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: velocityTracker.computeCurrentVelocity(velocityUnits); float xVelocity = velocityTracker.getXVelocity(); float yVelocity = velocityTracker.getYVelocity(); boolean negative; if (vertical) { negative = yVelocity < 0; if (xVelocity < 0) { xVelocity = -xVelocity; } if (xVelocity > maxMinorVelocity) { xVelocity = maxMinorVelocity; } } else { negative = xVelocity < 0; if (yVelocity < 0) { yVelocity = -yVelocity; } if (yVelocity > maxMinorVelocity) { yVelocity = maxMinorVelocity; } } float velocity = (float) Math.hypot(xVelocity, yVelocity); if (negative) { velocity = -velocity; } final int top = viewHandle.getTop(); final int left = viewHandle.getLeft(); if (Math.abs(velocity) < maxTapVelocity) { if (vertical ? (expanded && top < tapThreshold + topOffset) || (!expanded && top > bottomOffset + getBottom() - getTop() - handleHeight - tapThreshold) : (expanded && left < tapThreshold + topOffset) || (!expanded && left > bottomOffset + getRight() - getLeft() - handleWidth - tapThreshold)) { if (allowSingleTap) { playSoundEffect(SoundEffectConstants.CLICK); if (expanded) { animateClose(vertical ? top : left); } else { animateOpen(vertical ? top : left); } } else { performFling(vertical ? top : left, velocity, false); } } else { performFling(vertical ? top : left, velocity, false); } } else { performFling(vertical ? top : left, velocity, false); } break; } } return tracking || animating || super.onTouchEvent(event); } private void animateOpen(final int position) { prepareTracking(position); performFling(position, -maxAcceleration, true); } private void animateClose(final int position) { prepareTracking(position); performFling(position, maxAcceleration, true); } private void prepareTracking(final int position) { tracking = true; velocityTracker = VelocityTracker.obtain(); if (expanded) { if (animating) { animating = false; removeCallbacks(handler); } moveHandle(position); } else { animationAcceleration = maxAcceleration; animationVelocity = maxMajorVelocity; animationPosition = bottomOffset + (vertical ? getHeight() - handleHeight : getWidth() - handleWidth); moveHandle((int) animationPosition); animating = true; removeCallbacks(handler); animationLastTime = SystemClock.uptimeMillis(); animating = true; } } private void stopTracking() { viewHandle.setPressed(false); tracking = false; if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollEnded(); } if (velocityTracker != null) { velocityTracker.recycle(); } } private void performFling(final int position, final float velocity, final boolean always) { animationVelocity = velocity; animationPosition = position; if (expanded) { if (always || (velocity > maxMajorVelocity || (position > topOffset + (vertical ? handleHeight : handleWidth) && velocity > -maxMajorVelocity))) { animationAcceleration = maxAcceleration; if (velocity < 0) { animationVelocity = 0; } } else { animationAcceleration = -maxAcceleration; if (velocity > 0) { animationVelocity = 0; } } } else { if (!always && (velocity > maxMajorVelocity || (position > (vertical ? getHeight() : getWidth()) / 2 && velocity > -maxMajorVelocity))) { animationAcceleration = maxAcceleration; if (velocity < 0) { animationVelocity = 0; } } else { animationAcceleration = -maxAcceleration; if (velocity > 0) { animationVelocity = 0; } } } animationLastTime = SystemClock.uptimeMillis(); animating = true; removeCallbacks(handler); postDelayed(handler, ANIMATION_FRAME_DURATION); stopTracking(); } private void incrementAnimation() { final long now = SystemClock.uptimeMillis(); final float time = (now - animationLastTime) / 1000.0f; final float acceleration = animationAcceleration; final float velocity = animationVelocity; final float position = animationPosition; animationVelocity = velocity + (acceleration * time); animationPosition = position + (velocity * time) + (0.5f * acceleration * time * time); animationLastTime = now; } private void doAnimation() { if (animating) { incrementAnimation(); if (animationPosition >= bottomOffset + (vertical ? getHeight() : getWidth()) - 1) { animating = false; closeDrawer(); } else if (animationPosition < topOffset) { animating = false; openDrawer(); } else { moveHandle((int) animationPosition); postDelayed(handler, ANIMATION_FRAME_DURATION); } } } private void prepareContent() { if (!animating) { if (viewContent.isLayoutRequested()) { if (vertical) { final int height = getBottom() - getTop() - handleHeight - topOffset; viewContent.measure(MeasureSpec.makeMeasureSpec(getRight() - getLeft(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); viewContent.layout(0, topOffset + handleHeight, viewContent.getMeasuredWidth(), topOffset + handleHeight + viewContent.getMeasuredHeight()); } else { final int childWidth = viewHandle.getWidth(); final int width = getRight() - getLeft() - childWidth - topOffset; viewContent.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getBottom() - getTop(), MeasureSpec.EXACTLY)); viewContent.layout(childWidth + topOffset, 0, topOffset + childWidth + viewContent.getMeasuredWidth(), viewContent.getMeasuredHeight()); } } viewContent.getViewTreeObserver().dispatchOnPreDraw(); if (!viewContent.isHardwareAccelerated()) { viewContent.buildDrawingCache(); } viewContent.setVisibility(View.GONE); } } private void openDrawer() { moveHandle(DRAWER_EXPANDED); viewContent.setVisibility(View.VISIBLE); if (!expanded) { expanded = true; if (onDrawerOpenListener != null) { onDrawerOpenListener.onDrawerOpened(); } } } private void closeDrawer() { moveHandle(DRAWER_COLLAPSED); viewContent.setVisibility(View.GONE); viewContent.destroyDrawingCache(); if (expanded) { expanded = false; if (onDrawerCloseListener != null) { onDrawerCloseListener.onDrawerClosed(); } } } private void moveHandle(final int position) { if (vertical) { if (position == DRAWER_EXPANDED) { viewHandle.offsetTopAndBottom(topOffset - viewHandle.getTop()); invalidate(); } else if (position == DRAWER_COLLAPSED) { viewHandle.offsetTopAndBottom(bottomOffset + getBottom() - getTop() - handleHeight - viewHandle.getTop()); invalidate(); } else { final int top = viewHandle.getTop(); int deltaY = position - top; if (position < topOffset) { deltaY = topOffset - top; } else if (deltaY > bottomOffset + getBottom() - getTop() - handleHeight - top) { deltaY = bottomOffset + getBottom() - getTop() - handleHeight - top; } viewHandle.offsetTopAndBottom(deltaY); viewHandle.getHitRect(rectFrame); rectInvalidate.set(rectFrame); rectInvalidate.union(rectFrame.left, rectFrame.top - deltaY, rectFrame.right, rectFrame.bottom - deltaY); rectInvalidate.union(0, rectFrame.bottom - deltaY, getWidth(), rectFrame.bottom - deltaY + viewContent.getHeight()); invalidate(rectInvalidate); } } else { if (position == DRAWER_EXPANDED) { viewHandle.offsetLeftAndRight(topOffset - viewHandle.getLeft()); invalidate(); } else if (position == DRAWER_COLLAPSED) { viewHandle.offsetLeftAndRight(bottomOffset + getRight() - getLeft() - handleWidth - viewHandle.getLeft()); invalidate(); } else { final int left = viewHandle.getLeft(); int deltaX = position - left; if (position < topOffset) { deltaX = topOffset - left; } else if (deltaX > bottomOffset + getRight() - getLeft() - handleWidth - left) { deltaX = bottomOffset + getRight() - getLeft() - handleWidth - left; } viewHandle.offsetLeftAndRight(deltaX); viewHandle.getHitRect(rectFrame); rectInvalidate.set(rectFrame); rectInvalidate.union(rectFrame.left - deltaX, rectFrame.top, rectFrame.right - deltaX, rectFrame.bottom); rectInvalidate.union(rectFrame.right - deltaX, 0, rectFrame.right - deltaX + viewContent.getWidth(), getHeight()); invalidate(rectInvalidate); } } } @Override public void onInitializeAccessibilityEvent(@NonNull final AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setClassName(SlidingDrawer.class.getName()); } @Override public void onInitializeAccessibilityNodeInfo(@NonNull final AccessibilityNodeInfo nodeInfo) { super.onInitializeAccessibilityNodeInfo(nodeInfo); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { nodeInfo.setClassName(SlidingDrawer.class.getName()); } } /** * Indicates whether the drawer is scrolling or flinging. * * @return True if the drawer is scroller or flinging, false otherwise. */ public final boolean isMoving() { return tracking || animating; } /** * Indicates whether the drawer is currently fully opened. * * @return True if the drawer is opened, false otherwise. */ public final boolean isOpened() { return expanded; } /** * Locks the SlidingDrawer so that touch events are ignores. * * @see #unlock() */ public final void lock() { locked = true; } /** * Unlocks the SlidingDrawer so that touch events are processed. * * @see #lock() */ public final void unlock() { locked = false; } /** * Toggles the drawer open and close with an animation. * * @see #animateOpen() * @see #animateClose() * @see #toggle() * @see #open() * @see #close() */ public void animateToggle() { if (expanded) { animateClose(); } else { animateOpen(); } } /** * Opens the drawer with an animation. * * @see #animateToggle() * @see #animateClose() * @see #toggle() * @see #open() * @see #close() */ public void animateOpen() { prepareContent(); if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollStarted(); } animateOpen(vertical ? viewHandle.getTop() : viewHandle.getLeft()); sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollEnded(); } } /** * Closes the drawer with an animation. * * @see #animateToggle() * @see #animateOpen() * @see #toggle() * @see #open() * @see #close() */ public void animateClose() { prepareContent(); if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollStarted(); } animateClose(vertical ? viewHandle.getTop() : viewHandle.getLeft()); if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollEnded(); } } /** * Toggles the drawer open and close. Takes effect immediately. * * @see #animateToggle() * @see #animateOpen() * @see #animateClose() * @see #open() * @see #close() */ public void toggle() { if (expanded) { closeDrawer(); } else { openDrawer(); } invalidate(); requestLayout(); } /** * Opens the drawer immediately. * * @see #animateToggle() * @see #animateOpen() * @see #animateClose() * @see #toggle() * @see #close() */ public void open() { openDrawer(); invalidate(); requestLayout(); sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } /** * Closes the drawer immediately. * * @see #animateToggle() * @see #animateOpen() * @see #animateClose() * @see #toggle() * @see #open() */ public void close() { closeDrawer(); invalidate(); requestLayout(); } /** * Returns the handle of the drawer. * * @return The View representing the handle of the drawer, * identified by the "handle" id in XML. */ public final View getHandle() { return viewHandle; } /** * Returns the content of the drawer. * * @return The View representing the content of the drawer, * identified by the "content" id in XML. */ public final View getContent() { return viewContent; } /** * Sets the listener that receives a notification when the drawer becomes open. * * @param onDrawerOpenListener The listener to be notified when the drawer is opened. */ public final void setOnDrawerOpenListener(OnDrawerOpenListener onDrawerOpenListener) { this.onDrawerOpenListener = onDrawerOpenListener; } /** * Sets the listener that receives a notification when the drawer becomes close. * * @param onDrawerCloseListener The listener to be notified when the drawer is closed. */ public final void setOnDrawerCloseListener(OnDrawerCloseListener onDrawerCloseListener) { this.onDrawerCloseListener = onDrawerCloseListener; } /** * <p> Sets the listener that receives a notification when the drawer starts or ends a scroll. </p> * <p> A fling is considered as a scroll. A fling will also trigger a drawer opened or drawer closed event. </p> * * @param onDrawerScrollListener The listener to be notified when scrolling starts or stops. */ public final void setOnDrawerScrollListener(OnDrawerScrollListener onDrawerScrollListener) { this.onDrawerScrollListener = onDrawerScrollListener; } private final Runnable handler = new Runnable() { @Override public void run() { doAnimation(); } }; private class DrawerToggle implements OnClickListener { @Override public void onClick(final View view) { if (locked) { if (animateOnClick) { animateToggle(); } else { toggle(); } } } } }
SlidingDrawer/slidingdrawer/src/main/java/hollowsoft/slidingdrawer/SlidingDrawer.java
/* * Copyright 2014 Igor Morais * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package hollowsoft.slidingdrawer; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Build; import android.os.SystemClock; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.VelocityTracker; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; /** * <p> SlidingDrawer hides content out of the screen and allows the user to drag a handle * to bring the content on screen. SlidingDrawer can be used vertically or horizontally. </p> * * <p> A special widget composed of two children views: the handle, that the users drags, * and the content, attached to the handle and dragged with it. </p> * * <p> SlidingDrawer should be used as an overlay inside layouts. This means SlidingDrawer * should only be used inside of a FrameLayout or a RelativeLayout for instance. </p> * * <p> The size of the SlidingDrawer defines how much space the content will occupy once slid * out so SlidingDrawer should usually use match_parent for both its dimensions. </p> * * <p> Inside an XML layout, SlidingDrawer must define the id of the handle and of the * content: </p> * * <pre class="prettyprint"> * &lt;hollowsoft.slidingdrawer.SlidingDrawer * android:id="@+id/drawer" * android:layout_width="match_parent" * android:layout_height="match_parent" * android:handle="@+id/handle" * android:content="@+id/content"&gt; * * &lt;ImageView * android:id="@id/handle" * android:layout_width="88dip" * android:layout_height="44dip"/&gt; * * &lt;GridView * android:id="@id/content" * android:layout_width="match_parent" * android:layout_height="match_parent"/&gt; * * &lt;/hollowsoft.slidingdrawer.SlidingDrawer&gt; * </pre> * * @author Igor Morais */ public class SlidingDrawer extends ViewGroup { private static final int TAP_THRESHOLD = 6; private static final float MAX_TAP_VELOCITY = 100.0f; private static final float MAX_MINOR_VELOCITY = 150.0f; private static final float MAX_MAJOR_VELOCITY = 200.0f; private static final float MAX_ACCELERATION = 2000.0f; private static final int VELOCITY_UNITS = 1000; private static final int ANIMATION_FRAME_DURATION = 1000 / 60; private static final int DRAWER_EXPANDED = 501; private static final int DRAWER_COLLAPSED = 502; private static final int ORIENTATION_VERTICAL = 1; private int tapThreshold; private int maxTapVelocity; private int maxMinorVelocity; private int maxMajorVelocity; private int maxAcceleration; private int velocityUnits; private float animationAcceleration; private float animationVelocity; private float animationPosition; private long animationLastTime; private int touchDelta; private VelocityTracker velocityTracker; private final Rect rectFrame = new Rect(); private final Rect rectInvalidate = new Rect(); private boolean tracking; private boolean animating; private boolean locked; private boolean expanded; private int handleWidth; private int handleHeight; /** * Styleable. */ private boolean animateOnClick; private boolean allowSingleTap; private int topOffset; private int bottomOffset; private boolean vertical; private int handleId; private int contentId; private View viewHandle; private View viewContent; private OnDrawerOpenListener onDrawerOpenListener; private OnDrawerCloseListener onDrawerCloseListener; private OnDrawerScrollListener onDrawerScrollListener; /** * Creates a new SlidingDrawer from a specified set of attributes defined in XML. * * @param context The applications environment. * @param attributeSet The attributes defined in XML. */ public SlidingDrawer(final Context context, final AttributeSet attributeSet) { this(context, attributeSet, 0); } /** * Creates a new SlidingDrawer from a specified set of attributes defined in XML. * * @param context The applications environment. * @param attributeSet The attributes defined in XML. * @param defStyleAttr An attribute in the current theme that contains a reference * to a style resource that supplies default values for the view. * Can be 0 to not look for defaults. */ public SlidingDrawer(final Context context, final AttributeSet attributeSet, final int defStyleAttr) { super(context, attributeSet, defStyleAttr); loadStyleable(context, attributeSet, defStyleAttr, 0); } /** * Creates a new SlidingDrawer from a specified set of attributes defined in XML. * * @param context The applications environment. * @param attributeSet The attributes defined in XML. * @param defStyleAttr An attribute in the current theme that contains a reference * to a style resource that supplies default values for the view. * Can be 0 to not look for defaults. * @param defStyleRes A resource identifier of a style resource that supplies * default values for the view, used only if defStyleAttr is 0 * or can not be found in the theme. Can be 0 to not look for defaults. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public SlidingDrawer(final Context context, final AttributeSet attributeSet, final int defStyleAttr, final int defStyleRes) { super(context, attributeSet, defStyleAttr, defStyleRes); loadStyleable(context, attributeSet, defStyleAttr, defStyleRes); } private void loadStyleable(final Context context, final AttributeSet attributeSet, final int defStyleAttr, final int defStyleRes) { final TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.SlidingDrawer, defStyleAttr, defStyleRes); animateOnClick = typedArray.getBoolean(R.styleable.SlidingDrawer_animateOnClick, true); allowSingleTap = typedArray.getBoolean(R.styleable.SlidingDrawer_allowSingleTap, true); topOffset = (int) typedArray.getDimension(R.styleable.SlidingDrawer_topOffset, 0.0f); bottomOffset = (int) typedArray.getDimension(R.styleable.SlidingDrawer_bottomOffset, 0.0f); vertical = typedArray.getInt(R.styleable.SlidingDrawer_android_orientation, ORIENTATION_VERTICAL) == ORIENTATION_VERTICAL; handleId = typedArray.getResourceId(R.styleable.SlidingDrawer_handle, 0); if (handleId == 0) { throw new IllegalArgumentException("The handle attribute is required and must refer to a valid child."); } contentId = typedArray.getResourceId(R.styleable.SlidingDrawer_content, 0); if (contentId == 0) { throw new IllegalArgumentException("The content attribute is required and must refer to a valid child."); } if (handleId == contentId) { throw new IllegalArgumentException("The content and handle attributes must refer to different children."); } typedArray.recycle(); final float density = getResources().getDisplayMetrics().density; tapThreshold = (int) (TAP_THRESHOLD * density + 0.5f); maxTapVelocity = (int) (MAX_TAP_VELOCITY * density + 0.5f); maxMinorVelocity = (int) (MAX_MINOR_VELOCITY * density + 0.5f); maxMajorVelocity = (int) (MAX_MAJOR_VELOCITY * density + 0.5f); maxAcceleration = (int) (MAX_ACCELERATION * density + 0.5f); velocityUnits = (int) (VELOCITY_UNITS * density + 0.5f); setAlwaysDrawnWithCacheEnabled(false); } @Override protected void onFinishInflate() { super.onFinishInflate(); viewHandle = findViewById(handleId); if (viewHandle == null) { throw new IllegalArgumentException("The handle attribute is must refer to an existing child."); } viewHandle.setOnClickListener(new DrawerToggle()); viewContent = findViewById(contentId); if (viewContent == null) { throw new IllegalArgumentException("The content attribute is must refer to an existing child."); } viewContent.setVisibility(View.GONE); } @Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); final int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); final int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) { throw new IllegalStateException("The Drawer cannot have unspecified dimensions."); } measureChild(viewHandle, widthMeasureSpec, heightMeasureSpec); if (vertical) { final int height = heightSpecSize - viewHandle.getMeasuredHeight() - topOffset; viewContent.measure(MeasureSpec.makeMeasureSpec(widthSpecSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); } else { final int width = widthSpecSize - viewHandle.getMeasuredWidth() - topOffset; viewContent.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSpecSize, MeasureSpec.EXACTLY)); } setMeasuredDimension(widthSpecSize, heightSpecSize); } @Override protected void onLayout(final boolean changed, final int left, final int top, final int right, final int bottom) { if (!tracking) { final int width = right - left; final int height = bottom - top; int childLeft; int childTop; int childWidth = viewHandle.getMeasuredWidth(); int childHeight = viewHandle.getMeasuredHeight(); if (vertical) { childLeft = (width - childWidth) / 2; childTop = expanded ? topOffset : height - childHeight + bottomOffset; viewContent.layout(0, topOffset + childHeight, viewContent.getMeasuredWidth(), topOffset + childHeight + viewContent.getMeasuredHeight()); } else { childLeft = expanded ? topOffset : width - childWidth + bottomOffset; childTop = (height - childHeight) / 2; viewContent.layout(topOffset + childWidth, 0, topOffset + childWidth + viewContent.getMeasuredWidth(), viewContent.getMeasuredHeight()); } viewHandle.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); handleWidth = viewHandle.getWidth(); handleHeight = viewHandle.getHeight(); } } @Override protected void dispatchDraw(@NonNull final Canvas canvas) { final long drawingTime = getDrawingTime(); drawChild(canvas, viewHandle, drawingTime); if (tracking || animating) { final Bitmap bitmap = viewContent.getDrawingCache(); if (bitmap == null) { canvas.save(); canvas.translate(vertical ? 0 : viewHandle.getLeft() - topOffset, vertical ? viewHandle.getTop() - topOffset : 0); drawChild(canvas, viewContent, drawingTime); canvas.restore(); } else { if (vertical) { canvas.drawBitmap(bitmap, 0, viewHandle.getBottom(), null); } else { canvas.drawBitmap(bitmap, viewHandle.getRight(), 0, null); } } } else if (expanded) { drawChild(canvas, viewContent, drawingTime); } } @Override public boolean onInterceptTouchEvent(final MotionEvent event) { if (locked) { return false; } final int action = event.getAction(); final float x = event.getX(); final float y = event.getY(); viewHandle.getHitRect(rectFrame); if (!tracking && !rectFrame.contains((int) x, (int) y)) { return false; } if (action == MotionEvent.ACTION_DOWN) { tracking = true; viewHandle.setPressed(true); prepareContent(); if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollStarted(); } if (vertical) { final int top = viewHandle.getTop(); touchDelta = (int) y - top; prepareTracking(top); } else { final int left = viewHandle.getLeft(); touchDelta = (int) x - left; prepareTracking(left); } velocityTracker.addMovement(event); } return true; } @Override public boolean onTouchEvent(@NonNull final MotionEvent event) { if (locked) { return true; } if (tracking) { velocityTracker.addMovement(event); final int action = event.getAction(); switch (action) { case MotionEvent.ACTION_MOVE: moveHandle((int) (vertical ? event.getY() : event.getX()) - touchDelta); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: velocityTracker.computeCurrentVelocity(velocityUnits); float xVelocity = velocityTracker.getXVelocity(); float yVelocity = velocityTracker.getYVelocity(); boolean negative; if (vertical) { negative = yVelocity < 0; if (xVelocity < 0) { xVelocity = -xVelocity; } if (xVelocity > maxMinorVelocity) { xVelocity = maxMinorVelocity; } } else { negative = xVelocity < 0; if (yVelocity < 0) { yVelocity = -yVelocity; } if (yVelocity > maxMinorVelocity) { yVelocity = maxMinorVelocity; } } float velocity = (float) Math.hypot(xVelocity, yVelocity); if (negative) { velocity = -velocity; } final int top = viewHandle.getTop(); final int left = viewHandle.getLeft(); if (Math.abs(velocity) < maxTapVelocity) { if (vertical ? (expanded && top < tapThreshold + topOffset) || (!expanded && top > bottomOffset + getBottom() - getTop() - handleHeight - tapThreshold) : (expanded && left < tapThreshold + topOffset) || (!expanded && left > bottomOffset + getRight() - getLeft() - handleWidth - tapThreshold)) { if (allowSingleTap) { playSoundEffect(SoundEffectConstants.CLICK); if (expanded) { animateClose(vertical ? top : left); } else { animateOpen(vertical ? top : left); } } else { performFling(vertical ? top : left, velocity, false); } } else { performFling(vertical ? top : left, velocity, false); } } else { performFling(vertical ? top : left, velocity, false); } break; } } return tracking || animating || super.onTouchEvent(event); } private void animateOpen(final int position) { prepareTracking(position); performFling(position, -maxAcceleration, true); } private void animateClose(final int position) { prepareTracking(position); performFling(position, maxAcceleration, true); } private void prepareTracking(final int position) { tracking = true; velocityTracker = VelocityTracker.obtain(); if (expanded) { if (animating) { animating = false; removeCallbacks(handler); } moveHandle(position); } else { animationAcceleration = maxAcceleration; animationVelocity = maxMajorVelocity; animationPosition = bottomOffset + (vertical ? getHeight() - handleHeight : getWidth() - handleWidth); moveHandle((int) animationPosition); animating = true; removeCallbacks(handler); animationLastTime = SystemClock.uptimeMillis(); animating = true; } } private void stopTracking() { viewHandle.setPressed(false); tracking = false; if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollEnded(); } if (velocityTracker != null) { velocityTracker.recycle(); } } private void performFling(final int position, final float velocity, final boolean always) { animationVelocity = velocity; animationPosition = position; if (expanded) { if (always || (velocity > maxMajorVelocity || (position > topOffset + (vertical ? handleHeight : handleWidth) && velocity > -maxMajorVelocity))) { animationAcceleration = maxAcceleration; if (velocity < 0) { animationVelocity = 0; } } else { animationAcceleration = -maxAcceleration; if (velocity > 0) { animationVelocity = 0; } } } else { if (!always && (velocity > maxMajorVelocity || (position > (vertical ? getHeight() : getWidth()) / 2 && velocity > -maxMajorVelocity))) { animationAcceleration = maxAcceleration; if (velocity < 0) { animationVelocity = 0; } } else { animationAcceleration = -maxAcceleration; if (velocity > 0) { animationVelocity = 0; } } } animationLastTime = SystemClock.uptimeMillis(); animating = true; removeCallbacks(handler); postDelayed(handler, ANIMATION_FRAME_DURATION); stopTracking(); } private void incrementAnimation() { final long now = SystemClock.uptimeMillis(); final float time = (now - animationLastTime) / 1000.0f; final float acceleration = animationAcceleration; final float velocity = animationVelocity; final float position = animationPosition; animationVelocity = velocity + (acceleration * time); animationPosition = position + (velocity * time) + (0.5f * acceleration * time * time); animationLastTime = now; } private void doAnimation() { if (animating) { incrementAnimation(); if (animationPosition >= bottomOffset + (vertical ? getHeight() : getWidth()) - 1) { animating = false; closeDrawer(); } else if (animationPosition < topOffset) { animating = false; openDrawer(); } else { moveHandle((int) animationPosition); postDelayed(handler, ANIMATION_FRAME_DURATION); } } } private void prepareContent() { if (!animating) { if (viewContent.isLayoutRequested()) { if (vertical) { final int height = getBottom() - getTop() - handleHeight - topOffset; viewContent.measure(MeasureSpec.makeMeasureSpec(getRight() - getLeft(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); viewContent.layout(0, topOffset + handleHeight, viewContent.getMeasuredWidth(), topOffset + handleHeight + viewContent.getMeasuredHeight()); } else { final int childWidth = viewHandle.getWidth(); final int width = getRight() - getLeft() - childWidth - topOffset; viewContent.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getBottom() - getTop(), MeasureSpec.EXACTLY)); viewContent.layout(childWidth + topOffset, 0, topOffset + childWidth + viewContent.getMeasuredWidth(), viewContent.getMeasuredHeight()); } } viewContent.getViewTreeObserver().dispatchOnPreDraw(); if (!viewContent.isHardwareAccelerated()) { viewContent.buildDrawingCache(); } viewContent.setVisibility(View.GONE); } } private void openDrawer() { moveHandle(DRAWER_EXPANDED); viewContent.setVisibility(View.VISIBLE); if (!expanded) { expanded = true; if (onDrawerOpenListener != null) { onDrawerOpenListener.onDrawerOpened(); } } } private void closeDrawer() { moveHandle(DRAWER_COLLAPSED); viewContent.setVisibility(View.GONE); viewContent.destroyDrawingCache(); if (expanded) { expanded = false; if (onDrawerCloseListener != null) { onDrawerCloseListener.onDrawerClosed(); } } } private void moveHandle(final int position) { if (vertical) { if (position == DRAWER_EXPANDED) { viewHandle.offsetTopAndBottom(topOffset - viewHandle.getTop()); invalidate(); } else if (position == DRAWER_COLLAPSED) { viewHandle.offsetTopAndBottom(bottomOffset + getBottom() - getTop() - handleHeight - viewHandle.getTop()); invalidate(); } else { final int top = viewHandle.getTop(); int deltaY = position - top; if (position < topOffset) { deltaY = topOffset - top; } else if (deltaY > bottomOffset + getBottom() - getTop() - handleHeight - top) { deltaY = bottomOffset + getBottom() - getTop() - handleHeight - top; } viewHandle.offsetTopAndBottom(deltaY); viewHandle.getHitRect(rectFrame); rectInvalidate.set(rectFrame); rectInvalidate.union(rectFrame.left, rectFrame.top - deltaY, rectFrame.right, rectFrame.bottom - deltaY); rectInvalidate.union(0, rectFrame.bottom - deltaY, getWidth(), rectFrame.bottom - deltaY + viewContent.getHeight()); invalidate(rectInvalidate); } } else { if (position == DRAWER_EXPANDED) { viewHandle.offsetLeftAndRight(topOffset - viewHandle.getLeft()); invalidate(); } else if (position == DRAWER_COLLAPSED) { viewHandle.offsetLeftAndRight(bottomOffset + getRight() - getLeft() - handleWidth - viewHandle.getLeft()); invalidate(); } else { final int left = viewHandle.getLeft(); int deltaX = position - left; if (position < topOffset) { deltaX = topOffset - left; } else if (deltaX > bottomOffset + getRight() - getLeft() - handleWidth - left) { deltaX = bottomOffset + getRight() - getLeft() - handleWidth - left; } viewHandle.offsetLeftAndRight(deltaX); viewHandle.getHitRect(rectFrame); rectInvalidate.set(rectFrame); rectInvalidate.union(rectFrame.left - deltaX, rectFrame.top, rectFrame.right - deltaX, rectFrame.bottom); rectInvalidate.union(rectFrame.right - deltaX, 0, rectFrame.right - deltaX + viewContent.getWidth(), getHeight()); invalidate(rectInvalidate); } } } @Override public void onInitializeAccessibilityEvent(@NonNull final AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setClassName(SlidingDrawer.class.getName()); } @Override public void onInitializeAccessibilityNodeInfo(@NonNull final AccessibilityNodeInfo nodeInfo) { super.onInitializeAccessibilityNodeInfo(nodeInfo); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { nodeInfo.setClassName(SlidingDrawer.class.getName()); } } /** * Indicates whether the drawer is scrolling or flinging. * * @return True if the drawer is scroller or flinging, false otherwise. */ public final boolean isMoving() { return tracking || animating; } /** * Indicates whether the drawer is currently fully opened. * * @return True if the drawer is opened, false otherwise. */ public final boolean isOpened() { return expanded; } /** * Locks the SlidingDrawer so that touch events are ignores. * * @see #unlock() */ public final void lock() { locked = true; } /** * Unlocks the SlidingDrawer so that touch events are processed. * * @see #lock() */ public final void unlock() { locked = false; } /** * Toggles the drawer open and close with an animation. * * @see #animateOpen() * @see #animateClose() * @see #toggle() * @see #open() * @see #close() */ public void animateToggle() { if (expanded) { animateClose(); } else { animateOpen(); } } /** * Opens the drawer with an animation. * * @see #animateToggle() * @see #animateClose() * @see #toggle() * @see #open() * @see #close() */ public void animateOpen() { prepareContent(); if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollStarted(); } animateOpen(vertical ? viewHandle.getTop() : viewHandle.getLeft()); sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollEnded(); } } /** * Closes the drawer with an animation. * * @see #animateToggle() * @see #animateOpen() * @see #toggle() * @see #open() * @see #close() */ public void animateClose() { prepareContent(); if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollStarted(); } animateClose(vertical ? viewHandle.getTop() : viewHandle.getLeft()); if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollEnded(); } } /** * Toggles the drawer open and close. Takes effect immediately. * * @see #animateToggle() * @see #animateOpen() * @see #animateClose() * @see #open() * @see #close() */ public void toggle() { if (expanded) { closeDrawer(); } else { openDrawer(); } invalidate(); requestLayout(); } /** * Opens the drawer immediately. * * @see #animateToggle() * @see #animateOpen() * @see #animateClose() * @see #toggle() * @see #close() */ public void open() { openDrawer(); invalidate(); requestLayout(); sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } /** * Closes the drawer immediately. * * @see #animateToggle() * @see #animateOpen() * @see #animateClose() * @see #toggle() * @see #open() */ public void close() { closeDrawer(); invalidate(); requestLayout(); } /** * Returns the handle of the drawer. * * @return The View representing the handle of the drawer, * identified by the "handle" id in XML. */ public final View getHandle() { return viewHandle; } /** * Returns the content of the drawer. * * @return The View representing the content of the drawer, * identified by the "content" id in XML. */ public final View getContent() { return viewContent; } /** * Sets the listener that receives a notification when the drawer becomes open. * * @param onDrawerOpenListener The listener to be notified when the drawer is opened. */ public final void setOnDrawerOpenListener(OnDrawerOpenListener onDrawerOpenListener) { this.onDrawerOpenListener = onDrawerOpenListener; } /** * Sets the listener that receives a notification when the drawer becomes close. * * @param onDrawerCloseListener The listener to be notified when the drawer is closed. */ public final void setOnDrawerCloseListener(OnDrawerCloseListener onDrawerCloseListener) { this.onDrawerCloseListener = onDrawerCloseListener; } /** * <p> Sets the listener that receives a notification when the drawer starts or ends a scroll. </p> * <p> A fling is considered as a scroll. A fling will also trigger a drawer opened or drawer closed event. </p> * * @param onDrawerScrollListener The listener to be notified when scrolling starts or stops. */ public final void setOnDrawerScrollListener(OnDrawerScrollListener onDrawerScrollListener) { this.onDrawerScrollListener = onDrawerScrollListener; } private final Runnable handler = new Runnable() { @Override public void run() { doAnimation(); } }; private class DrawerToggle implements OnClickListener { @Override public void onClick(final View view) { if (locked) { if (animateOnClick) { animateToggle(); } else { toggle(); } } } } }
Remove deprecated method
SlidingDrawer/slidingdrawer/src/main/java/hollowsoft/slidingdrawer/SlidingDrawer.java
Remove deprecated method
<ide><path>lidingDrawer/slidingdrawer/src/main/java/hollowsoft/slidingdrawer/SlidingDrawer.java <ide> maxMajorVelocity = (int) (MAX_MAJOR_VELOCITY * density + 0.5f); <ide> maxAcceleration = (int) (MAX_ACCELERATION * density + 0.5f); <ide> velocityUnits = (int) (VELOCITY_UNITS * density + 0.5f); <del> <del> setAlwaysDrawnWithCacheEnabled(false); <ide> } <ide> <ide> @Override
Java
mit
939fd921d2b152962939f35fe7b5a6b32c1a128f
0
swaplicado/siie32
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package erp.cfd; import erp.client.SClientInterface; import erp.data.SDataConstants; import erp.data.SDataUtilities; import erp.lib.SLibConstants; import erp.mhrs.data.SDataFormerPayrollEmp; import erp.mod.SModConsts; import erp.mod.hrs.db.SDbPayrollReceipt; import erp.mod.hrs.db.SDbPayrollReceiptIssue; import erp.mod.hrs.db.SHrsCfdUtils; import erp.mod.hrs.db.SHrsUtils; import erp.mtrn.data.SCfdUtils; import erp.mtrn.data.SDataCfd; import erp.mtrn.data.SDataDps; import erp.print.SDataConstantsPrint; import java.awt.Cursor; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Date; import sa.lib.SLibConsts; import sa.lib.SLibUtils; import sa.lib.db.SDbRegistry; import sa.lib.gui.SGuiClient; import sa.lib.gui.SGuiConsts; import sa.lib.gui.SGuiSession; import sa.lib.gui.SGuiUtils; import sa.lib.gui.SGuiValidation; /** * * @author Juan Barajas */ public class SDialogResult extends sa.lib.gui.bean.SBeanFormDialog { protected SClientInterface miClient; protected ArrayList<SDataCfd> maCfds; protected ArrayList<int[]> manPayrollReceiptsId; protected int mnTotalStamps; protected Date mtCancellationDate; protected boolean mbValidateStamp; protected boolean mbFirstTime; protected int mnSubtypeCfd; protected int mnNumCopies; /** * Creates new form SDialogResult */ public SDialogResult(SGuiClient client, String title, int subType) { setFormSettings(client, SGuiConsts.BEAN_FORM_EDIT, SModConsts.TRN_CFD, subType, title); initComponents(); initComponentsCustom(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jpInformation = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); jlTotalToProcess = new javax.swing.JLabel(); moIntTotalToProcess = new sa.lib.gui.bean.SBeanFieldInteger(); jPanel21 = new javax.swing.JPanel(); jlTotalCorrect = new javax.swing.JLabel(); moIntTotalCorrect = new sa.lib.gui.bean.SBeanFieldInteger(); jPanel22 = new javax.swing.JPanel(); jlTotalIncorrect = new javax.swing.JLabel(); moIntTotalIncorrect = new sa.lib.gui.bean.SBeanFieldInteger(); jPanel4 = new javax.swing.JPanel(); jlTotalProcess = new javax.swing.JLabel(); moIntTotalProcess = new sa.lib.gui.bean.SBeanFieldInteger(); jpStampInfo = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jlTotalStamps = new javax.swing.JLabel(); moIntTotalStamp = new sa.lib.gui.bean.SBeanFieldInteger(); jPanel24 = new javax.swing.JPanel(); jlTotalConsumed = new javax.swing.JLabel(); moIntTotalConsumed = new sa.lib.gui.bean.SBeanFieldInteger(); jPanel25 = new javax.swing.JPanel(); jlTotalAvailables = new javax.swing.JLabel(); moIntTotalAvailables = new sa.lib.gui.bean.SBeanFieldInteger(); jpDetail = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jtaMessage = new javax.swing.JTextArea(); setModal(true); addWindowListener(new java.awt.event.WindowAdapter() { public void windowActivated(java.awt.event.WindowEvent evt) { formWindowActivated(evt); } }); jPanel1.setLayout(new java.awt.BorderLayout(0, 5)); jpInformation.setBorder(javax.swing.BorderFactory.createTitledBorder("Resumen:")); jpInformation.setLayout(new java.awt.GridLayout(1, 2, 0, 5)); jPanel5.setLayout(new java.awt.GridLayout(4, 1, 0, 5)); jPanel6.setLayout(new java.awt.FlowLayout(0, 5, 0)); jlTotalToProcess.setText("CFDI a procesar:"); jlTotalToProcess.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel6.add(jlTotalToProcess); moIntTotalToProcess.setEditable(false); jPanel6.add(moIntTotalToProcess); jPanel5.add(jPanel6); jPanel21.setLayout(new java.awt.FlowLayout(0, 5, 0)); jlTotalCorrect.setText("Procesados correctamente:"); jlTotalCorrect.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel21.add(jlTotalCorrect); moIntTotalCorrect.setEditable(false); jPanel21.add(moIntTotalCorrect); jPanel5.add(jPanel21); jPanel22.setLayout(new java.awt.FlowLayout(0, 5, 0)); jlTotalIncorrect.setText("Procesados incorrectamente:"); jlTotalIncorrect.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel22.add(jlTotalIncorrect); moIntTotalIncorrect.setEditable(false); jPanel22.add(moIntTotalIncorrect); jPanel5.add(jPanel22); jPanel4.setLayout(new java.awt.FlowLayout(0, 5, 0)); jlTotalProcess.setText("CFDI procesados:"); jlTotalProcess.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel4.add(jlTotalProcess); moIntTotalProcess.setEditable(false); jPanel4.add(moIntTotalProcess); jPanel5.add(jPanel4); jpInformation.add(jPanel5); jpStampInfo.setLayout(new java.awt.GridLayout(4, 1, 0, 5)); jPanel7.setLayout(new java.awt.FlowLayout(0, 5, 0)); jlTotalStamps.setText("Timbres disponibles:"); jlTotalStamps.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel7.add(jlTotalStamps); moIntTotalStamp.setEditable(false); jPanel7.add(moIntTotalStamp); jpStampInfo.add(jPanel7); jPanel24.setLayout(new java.awt.FlowLayout(0, 5, 0)); jlTotalConsumed.setText("Timbres consumidos:"); jlTotalConsumed.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel24.add(jlTotalConsumed); moIntTotalConsumed.setEditable(false); jPanel24.add(moIntTotalConsumed); jpStampInfo.add(jPanel24); jPanel25.setLayout(new java.awt.FlowLayout(0, 5, 0)); jlTotalAvailables.setText("Timbres restantes:"); jlTotalAvailables.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel25.add(jlTotalAvailables); moIntTotalAvailables.setEditable(false); jPanel25.add(moIntTotalAvailables); jpStampInfo.add(jPanel25); jpInformation.add(jpStampInfo); jPanel1.add(jpInformation, java.awt.BorderLayout.NORTH); jpDetail.setBorder(javax.swing.BorderFactory.createTitledBorder("Detalle:")); jpDetail.setLayout(new java.awt.BorderLayout()); jPanel2.setLayout(new java.awt.BorderLayout()); jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); jScrollPane1.setAutoscrolls(true); jtaMessage.setEditable(false); jtaMessage.setColumns(20); jtaMessage.setFont(new java.awt.Font("Monospaced", 0, 11)); // NOI18N jtaMessage.setRows(5); jtaMessage.setFocusable(false); jtaMessage.setOpaque(false); jScrollPane1.setViewportView(jtaMessage); jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER); jpDetail.add(jPanel2, java.awt.BorderLayout.CENTER); jPanel1.add(jpDetail, java.awt.BorderLayout.CENTER); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated windowsActivated(); }//GEN-LAST:event_formWindowActivated // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel21; private javax.swing.JPanel jPanel22; private javax.swing.JPanel jPanel24; private javax.swing.JPanel jPanel25; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel jlTotalAvailables; private javax.swing.JLabel jlTotalConsumed; private javax.swing.JLabel jlTotalCorrect; private javax.swing.JLabel jlTotalIncorrect; private javax.swing.JLabel jlTotalProcess; private javax.swing.JLabel jlTotalStamps; private javax.swing.JLabel jlTotalToProcess; private javax.swing.JPanel jpDetail; private javax.swing.JPanel jpInformation; private javax.swing.JPanel jpStampInfo; private javax.swing.JTextArea jtaMessage; private sa.lib.gui.bean.SBeanFieldInteger moIntTotalAvailables; private sa.lib.gui.bean.SBeanFieldInteger moIntTotalConsumed; private sa.lib.gui.bean.SBeanFieldInteger moIntTotalCorrect; private sa.lib.gui.bean.SBeanFieldInteger moIntTotalIncorrect; private sa.lib.gui.bean.SBeanFieldInteger moIntTotalProcess; private sa.lib.gui.bean.SBeanFieldInteger moIntTotalStamp; private sa.lib.gui.bean.SBeanFieldInteger moIntTotalToProcess; // End of variables declaration//GEN-END:variables private void windowsActivated() { if (mbFirstTime) { mbFirstTime = false; try { process(); } catch (Exception e) { SLibUtils.printException(this, e); } } } private void initComponentsCustom() { SGuiUtils.setWindowBounds(this, 720, 450); jbSave.setEnabled(false); jbCancel.setText("Aceptar"); moIntTotalToProcess.setIntegerSettings(SGuiUtils.getLabelName(jlTotalToProcess), SGuiConsts.GUI_TYPE_INT, true); moIntTotalProcess.setIntegerSettings(SGuiUtils.getLabelName(jlTotalProcess), SGuiConsts.GUI_TYPE_INT, true); moIntTotalCorrect.setIntegerSettings(SGuiUtils.getLabelName(jlTotalCorrect), SGuiConsts.GUI_TYPE_INT, true); moIntTotalIncorrect.setIntegerSettings(SGuiUtils.getLabelName(jlTotalIncorrect), SGuiConsts.GUI_TYPE_INT, true); moIntTotalStamp.setIntegerSettings(SGuiUtils.getLabelName(jlTotalStamps), SGuiConsts.GUI_TYPE_INT, true); moIntTotalConsumed.setIntegerSettings(SGuiUtils.getLabelName(jlTotalConsumed), SGuiConsts.GUI_TYPE_INT, true); moIntTotalAvailables.setIntegerSettings(SGuiUtils.getLabelName(jlTotalAvailables), SGuiConsts.GUI_TYPE_INT, true); moFields.addField(moIntTotalToProcess); moFields.addField(moIntTotalProcess); moFields.addField(moIntTotalCorrect); moFields.addField(moIntTotalIncorrect); moFields.addField(moIntTotalStamp); moFields.addField(moIntTotalConsumed); moFields.addField(moIntTotalAvailables); moFields.setFormButton(jbSave); } private void process() throws Exception { miClient.getFrame().setCursor(new Cursor(Cursor.WAIT_CURSOR)); if (manPayrollReceiptsId != null) { processPayroll(); } else if (maCfds != null) { processCfd(); } } public void processPayroll() { int number = 0; int cfdsProcessed = 0; int cfdsCorrect = 0; int cfdsIncorrect = 0; String detailMessage = ""; SDbPayrollReceiptIssue receiptIssue = null; if (manPayrollReceiptsId != null) { receiptIssue = new SDbPayrollReceiptIssue(); for (int[] key : manPayrollReceiptsId) { cfdsProcessed ++; try { switch (mnFormSubtype) { case SCfdConsts.PROC_REQ_STAMP: receiptIssue.read(miClient.getSession(), new int[] { key[0], key[1], key[2] }); if (receiptIssue.getPkIssueId() != SLibConsts.UNDEFINED) { number = SHrsUtils.getPayrollReceiptNextNumber(miClient.getSession(), receiptIssue.getNumberSeries()); if (receiptIssue.getNumber() == SLibConsts.UNDEFINED) { receiptIssue.saveField(miClient.getSession().getStatement(), new int[] { key[0], key[1], key[2] }, SDbPayrollReceiptIssue.FIELD_NUMBER, number); } } SHrsCfdUtils.computeSignCfdi(miClient.getSession(), new int[] { key[0], key[1], key[2] }); detailMessage += (receiptIssue.getNumberSeries().length() > 0 ? receiptIssue.getNumberSeries() + "-" : "") + number + " Timbrado" + (miClient.getSessionXXX().getParamsCompany().getIsCfdiSendingAutomaticHrs() ? " y enviado.\n" : ".\n"); cfdsCorrect ++; break; } } catch(Exception e) { detailMessage += "NOM-" + number + " " + e.getMessage() + "\n"; cfdsIncorrect++; } if (mnTotalStamps > 0) { updateForm(cfdsProcessed, cfdsCorrect, cfdsIncorrect, detailMessage, mnTotalStamps); } else { updateForm(cfdsProcessed, cfdsCorrect, cfdsIncorrect, detailMessage); } update(getGraphics()); jScrollPane1.getVerticalScrollBar().setValue(jScrollPane1.getVerticalScrollBar().getMaximum()); } miClient.getFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } public void processCfd() throws Exception { int cfdsProcessed = 0; int cfdsCorrect = 0; int cfdsIncorrect = 0; SDataFormerPayrollEmp payrollEmp = null; SDbPayrollReceipt payrollReceipt = null; SDbPayrollReceiptIssue payrollReceiptIssue = null; SDataDps dps = null; String detailMessage = ""; String numberSeries = ""; String number = ""; String sSql = ""; ResultSet resultSet = null; moIntTotalToProcess.setValue(maCfds.size()); if (maCfds != null) { for(SDataCfd cfd : maCfds) { cfdsProcessed++; switch (cfd.getFkCfdTypeId()) { case SCfdConsts.CFD_TYPE_DPS: dps = (SDataDps) SDataUtilities.readRegistry(miClient, SDataConstants.TRN_DPS, new int[] { cfd.getFkDpsYearId_n(), cfd.getFkDpsDocId_n() }, SLibConstants.EXEC_MODE_SILENT); numberSeries = dps.getNumberSeries(); number = dps.getNumber(); break; case SCfdConsts.CFD_TYPE_PAYROLL: switch (mnSubtypeCfd) { case SCfdConsts.CFDI_PAYROLL_VER_OLD: payrollEmp = (SDataFormerPayrollEmp) SDataUtilities.readRegistry(miClient, SDataConstants.HRS_FORMER_PAYR_EMP, new int[] { cfd.getFkPayrollPayrollId_n(), cfd.getFkPayrollEmployeeId_n() }, SLibConstants.EXEC_MODE_SILENT); numberSeries = payrollEmp.getNumberSeries(); number = "" + payrollEmp.getNumber(); break; case SCfdConsts.CFDI_PAYROLL_VER_CUR: /* payrollReceipt = new SDbPayrollReceipt(); payrollReceipt.read(miClient.getSession(), new int[] { cfd.getFkPayrollReceiptPayrollId_n(), cfd.getFkPayrollReceiptEmployeeId_n() }); if (payrollReceipt.getPayrollReceiptIssues() != null) { numberSeries = payrollReceipt.getPayrollReceiptIssues().getNumberSeries(); number = "" + payrollReceipt.getPayrollReceiptIssues().getNumber(); } */ // Read Issue last: sSql = "SELECT id_iss " + "FROM " + SModConsts.TablesMap.get(SModConsts.HRS_PAY_RCP_ISS) + " " + "WHERE id_pay = " + cfd.getFkPayrollReceiptPayrollId_n() + " AND id_emp = " + cfd.getFkPayrollReceiptEmployeeId_n() + " " + "ORDER BY id_iss DESC LIMIT 1"; resultSet = miClient.getSession().getDatabase().getConnection().createStatement().executeQuery(sSql); if (resultSet.next()) { payrollReceiptIssue = new SDbPayrollReceiptIssue(); numberSeries = (String) payrollReceiptIssue.readField(miClient.getSession().getDatabase().getConnection().createStatement(), new int[] { cfd.getFkPayrollReceiptPayrollId_n(), cfd.getFkPayrollReceiptEmployeeId_n(), resultSet.getInt("id_iss") }, SDbPayrollReceiptIssue.FIELD_NUMBER_SERIES); number = "" + (int) payrollReceiptIssue.readField(miClient.getSession().getDatabase().getConnection().createStatement(), new int[] { cfd.getFkPayrollReceiptPayrollId_n(), cfd.getFkPayrollReceiptEmployeeId_n(), resultSet.getInt("id_iss") }, SDbPayrollReceiptIssue.FIELD_NUMBER); } break; default: throw new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN); } break; default: throw new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN); } try { switch (mnFormSubtype) { case SCfdConsts.PROC_REQ_STAMP: SCfdUtils.signCfdi(miClient, cfd, mnSubtypeCfd, false); detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " Timbrado.\n"; break; case SCfdConsts.PROC_REQ_ANNUL: SCfdUtils.cancelCfdi(miClient, cfd, mnSubtypeCfd, mtCancellationDate, mbValidateStamp, false); detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " Anulado.\n"; break; case SCfdConsts.PROC_PRT_DOC: SCfdUtils.printCfd(miClient, cfd.getFkCfdTypeId(), cfd, SDataConstantsPrint.PRINT_MODE_STREAM, mnNumCopies, mnSubtypeCfd, false); detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " Impreso.\n"; break; case SCfdConsts.PROC_PRT_ACK_ANNUL: SCfdUtils.printAcknowledgmentCancellationCfd(miClient, cfd, SDataConstantsPrint.PRINT_MODE_STREAM, mnSubtypeCfd); detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " Impreso.\n"; break; case SCfdConsts.PROC_SND_DOC: SCfdUtils.sendCfd(miClient, cfd.getFkCfdTypeId(), cfd, mnSubtypeCfd, false); detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " Enviado.\n"; break; case SCfdConsts.PROC_REQ_STAMP_AND_SND: if (miClient.getSessionXXX().getParamsCompany().getIsCfdiSendingAutomaticHrs()) { SCfdUtils.signAndSendCfdi(miClient, cfd, mnSubtypeCfd, false); } else { SCfdUtils.signCfdi(miClient, cfd, mnSubtypeCfd, false); } detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + "Timbrado" + (miClient.getSessionXXX().getParamsCompany().getIsCfdiSendingAutomaticHrs() ? " y enviado.\n" : ".\n"); break; case SCfdConsts.PROC_REQ_ANNUL_AND_SND: if (miClient.getSessionXXX().getParamsCompany().getIsCfdiSendingAutomaticHrs()) { SCfdUtils.cancelAndSendCfdi(miClient, cfd, mnSubtypeCfd, mtCancellationDate, mbValidateStamp, false); } else { SCfdUtils.cancelCfdi(miClient, cfd, mnSubtypeCfd, mtCancellationDate, mbValidateStamp, false); } detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " Anulado" + (miClient.getSessionXXX().getParamsCompany().getIsCfdiSendingAutomaticHrs() ? " y enviado.\n" : ".\n"); break; case SCfdConsts.PROC_REQ_VERIFY: SCfdUtils.verifyCfdi(miClient, cfd, mnSubtypeCfd); detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " Enviado.\n"; break; default: } cfdsCorrect++; } catch(Exception e) { detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " " + e.getMessage() + "\n"; cfdsIncorrect++; } if (mnTotalStamps > 0) { updateForm(cfdsProcessed, cfdsCorrect, cfdsIncorrect, detailMessage, mnTotalStamps); } else { updateForm(cfdsProcessed, cfdsCorrect, cfdsIncorrect, detailMessage); } update(getGraphics()); jScrollPane1.getVerticalScrollBar().setValue(jScrollPane1.getVerticalScrollBar().getMaximum()); } miClient.getFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } public synchronized SGuiSession getSession() { SGuiSession session = new SGuiSession((SGuiClient) miClient); session.setUser(miClient.getSessionXXX().getUser()); // XXX this must be replaced session.setSystemDate(miClient.getSessionXXX().getSystemDate()); session.setCurrentDate(miClient.getSessionXXX().getWorkingDate()); session.setUserTs(miClient.getSessionXXX().getSystemDate()); session.setDatabase(miClient.getSession().getDatabase()); return session; } private void updateForm(final int totalProcess, final int totalCorrect, final int totalIncorrect, final String message, final int totalStamp) { moIntTotalProcess.setValue(totalProcess); moIntTotalCorrect.setValue(totalCorrect); moIntTotalIncorrect.setValue(totalIncorrect); moIntTotalStamp.setValue(totalStamp); moIntTotalConsumed.setValue(totalCorrect); moIntTotalAvailables.setValue(totalStamp - totalCorrect); jtaMessage.setText(message); } public void updateForm(final int totalProcess, final int totalCorrect, final int totalIncorrect, final String message) { moIntTotalProcess.setValue(totalProcess); moIntTotalCorrect.setValue(totalCorrect); moIntTotalIncorrect.setValue(totalIncorrect); moIntTotalStamp.setValue(0); moIntTotalConsumed.setValue(0); moIntTotalAvailables.setValue(0); jtaMessage.setText(message); } public void setFormParams(final SClientInterface client, final ArrayList<SDataCfd> cfds, final ArrayList<int[]> payrollReceipts, final int totalStamp, Date cancellationDate, final boolean validateStamp, final int subtypeCfd) { mbFirstTime = true; miClient = client; maCfds = cfds; manPayrollReceiptsId = payrollReceipts; mnTotalStamps = totalStamp; mtCancellationDate = cancellationDate; mbValidateStamp = validateStamp; mnSubtypeCfd = subtypeCfd; } public void setNumberCopies(final int numCopies) { mnNumCopies = numCopies; } @Override public void addAllListeners() { } @Override public void removeAllListeners() { } @Override public void reloadCatalogues() { } @Override public void setRegistry(SDbRegistry registry) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @Override public SDbRegistry getRegistry() throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @Override public SGuiValidation validateForm() { SGuiValidation validation = moFields.validateFields(); return validation; } }
src/erp/cfd/SDialogResult.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package erp.cfd; import erp.client.SClientInterface; import erp.data.SDataConstants; import erp.data.SDataUtilities; import erp.lib.SLibConstants; import erp.mhrs.data.SDataFormerPayrollEmp; import erp.mod.SModConsts; import erp.mod.hrs.db.SDbPayrollReceipt; import erp.mod.hrs.db.SDbPayrollReceiptIssue; import erp.mod.hrs.db.SHrsCfdUtils; import erp.mod.hrs.db.SHrsUtils; import erp.mtrn.data.SCfdUtils; import erp.mtrn.data.SDataCfd; import erp.mtrn.data.SDataDps; import erp.print.Print; import erp.print.SDataConstantsPrint; import java.awt.Cursor; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Date; import sa.lib.SLibConsts; import sa.lib.SLibUtils; import sa.lib.db.SDbRegistry; import sa.lib.gui.SGuiClient; import sa.lib.gui.SGuiConsts; import sa.lib.gui.SGuiSession; import sa.lib.gui.SGuiUtils; import sa.lib.gui.SGuiValidation; /** * * @author Juan Barajas */ public class SDialogResult extends sa.lib.gui.bean.SBeanFormDialog { protected SClientInterface miClient; protected ArrayList<SDataCfd> maCfds; protected ArrayList<int[]> manPayrollReceiptsId; protected int mnTotalStamps; protected Date mtCancellationDate; protected boolean mbValidateStamp; protected boolean mbFirstTime; protected int mnSubtypeCfd; protected int mnNumCopies; /** * Creates new form SDialogResult */ public SDialogResult(SGuiClient client, String title, int subType) { setFormSettings(client, SGuiConsts.BEAN_FORM_EDIT, SModConsts.TRN_CFD, subType, title); initComponents(); initComponentsCustom(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jpInformation = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); jlTotalToProcess = new javax.swing.JLabel(); moIntTotalToProcess = new sa.lib.gui.bean.SBeanFieldInteger(); jPanel21 = new javax.swing.JPanel(); jlTotalCorrect = new javax.swing.JLabel(); moIntTotalCorrect = new sa.lib.gui.bean.SBeanFieldInteger(); jPanel22 = new javax.swing.JPanel(); jlTotalIncorrect = new javax.swing.JLabel(); moIntTotalIncorrect = new sa.lib.gui.bean.SBeanFieldInteger(); jPanel4 = new javax.swing.JPanel(); jlTotalProcess = new javax.swing.JLabel(); moIntTotalProcess = new sa.lib.gui.bean.SBeanFieldInteger(); jpStampInfo = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jlTotalStamps = new javax.swing.JLabel(); moIntTotalStamp = new sa.lib.gui.bean.SBeanFieldInteger(); jPanel24 = new javax.swing.JPanel(); jlTotalConsumed = new javax.swing.JLabel(); moIntTotalConsumed = new sa.lib.gui.bean.SBeanFieldInteger(); jPanel25 = new javax.swing.JPanel(); jlTotalAvailables = new javax.swing.JLabel(); moIntTotalAvailables = new sa.lib.gui.bean.SBeanFieldInteger(); jpDetail = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jtaMessage = new javax.swing.JTextArea(); setModal(true); addWindowListener(new java.awt.event.WindowAdapter() { public void windowActivated(java.awt.event.WindowEvent evt) { formWindowActivated(evt); } }); jPanel1.setLayout(new java.awt.BorderLayout(0, 5)); jpInformation.setBorder(javax.swing.BorderFactory.createTitledBorder("Resumen:")); jpInformation.setLayout(new java.awt.GridLayout(1, 2, 0, 5)); jPanel5.setLayout(new java.awt.GridLayout(4, 1, 0, 5)); jPanel6.setLayout(new java.awt.FlowLayout(0, 5, 0)); jlTotalToProcess.setText("CFDI a procesar:"); jlTotalToProcess.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel6.add(jlTotalToProcess); moIntTotalToProcess.setEditable(false); jPanel6.add(moIntTotalToProcess); jPanel5.add(jPanel6); jPanel21.setLayout(new java.awt.FlowLayout(0, 5, 0)); jlTotalCorrect.setText("Procesados correctamente:"); jlTotalCorrect.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel21.add(jlTotalCorrect); moIntTotalCorrect.setEditable(false); jPanel21.add(moIntTotalCorrect); jPanel5.add(jPanel21); jPanel22.setLayout(new java.awt.FlowLayout(0, 5, 0)); jlTotalIncorrect.setText("Procesados incorrectamente:"); jlTotalIncorrect.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel22.add(jlTotalIncorrect); moIntTotalIncorrect.setEditable(false); jPanel22.add(moIntTotalIncorrect); jPanel5.add(jPanel22); jPanel4.setLayout(new java.awt.FlowLayout(0, 5, 0)); jlTotalProcess.setText("CFDI procesados:"); jlTotalProcess.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel4.add(jlTotalProcess); moIntTotalProcess.setEditable(false); jPanel4.add(moIntTotalProcess); jPanel5.add(jPanel4); jpInformation.add(jPanel5); jpStampInfo.setLayout(new java.awt.GridLayout(4, 1, 0, 5)); jPanel7.setLayout(new java.awt.FlowLayout(0, 5, 0)); jlTotalStamps.setText("Timbres disponibles:"); jlTotalStamps.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel7.add(jlTotalStamps); moIntTotalStamp.setEditable(false); jPanel7.add(moIntTotalStamp); jpStampInfo.add(jPanel7); jPanel24.setLayout(new java.awt.FlowLayout(0, 5, 0)); jlTotalConsumed.setText("Timbres consumidos:"); jlTotalConsumed.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel24.add(jlTotalConsumed); moIntTotalConsumed.setEditable(false); jPanel24.add(moIntTotalConsumed); jpStampInfo.add(jPanel24); jPanel25.setLayout(new java.awt.FlowLayout(0, 5, 0)); jlTotalAvailables.setText("Timbres restantes:"); jlTotalAvailables.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel25.add(jlTotalAvailables); moIntTotalAvailables.setEditable(false); jPanel25.add(moIntTotalAvailables); jpStampInfo.add(jPanel25); jpInformation.add(jpStampInfo); jPanel1.add(jpInformation, java.awt.BorderLayout.NORTH); jpDetail.setBorder(javax.swing.BorderFactory.createTitledBorder("Detalle:")); jpDetail.setLayout(new java.awt.BorderLayout()); jPanel2.setLayout(new java.awt.BorderLayout()); jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); jScrollPane1.setAutoscrolls(true); jtaMessage.setEditable(false); jtaMessage.setColumns(20); jtaMessage.setFont(new java.awt.Font("Monospaced", 0, 11)); // NOI18N jtaMessage.setRows(5); jtaMessage.setFocusable(false); jtaMessage.setOpaque(false); jScrollPane1.setViewportView(jtaMessage); jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER); jpDetail.add(jPanel2, java.awt.BorderLayout.CENTER); jPanel1.add(jpDetail, java.awt.BorderLayout.CENTER); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated windowsActivated(); }//GEN-LAST:event_formWindowActivated // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel21; private javax.swing.JPanel jPanel22; private javax.swing.JPanel jPanel24; private javax.swing.JPanel jPanel25; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel jlTotalAvailables; private javax.swing.JLabel jlTotalConsumed; private javax.swing.JLabel jlTotalCorrect; private javax.swing.JLabel jlTotalIncorrect; private javax.swing.JLabel jlTotalProcess; private javax.swing.JLabel jlTotalStamps; private javax.swing.JLabel jlTotalToProcess; private javax.swing.JPanel jpDetail; private javax.swing.JPanel jpInformation; private javax.swing.JPanel jpStampInfo; private javax.swing.JTextArea jtaMessage; private sa.lib.gui.bean.SBeanFieldInteger moIntTotalAvailables; private sa.lib.gui.bean.SBeanFieldInteger moIntTotalConsumed; private sa.lib.gui.bean.SBeanFieldInteger moIntTotalCorrect; private sa.lib.gui.bean.SBeanFieldInteger moIntTotalIncorrect; private sa.lib.gui.bean.SBeanFieldInteger moIntTotalProcess; private sa.lib.gui.bean.SBeanFieldInteger moIntTotalStamp; private sa.lib.gui.bean.SBeanFieldInteger moIntTotalToProcess; // End of variables declaration//GEN-END:variables private void windowsActivated() { if (mbFirstTime) { mbFirstTime = false; try { process(); } catch (Exception e) { SLibUtils.printException(this, e); } } } private void initComponentsCustom() { SGuiUtils.setWindowBounds(this, 720, 450); jbSave.setEnabled(false); jbCancel.setText("Aceptar"); moIntTotalToProcess.setIntegerSettings(SGuiUtils.getLabelName(jlTotalToProcess), SGuiConsts.GUI_TYPE_INT, true); moIntTotalProcess.setIntegerSettings(SGuiUtils.getLabelName(jlTotalProcess), SGuiConsts.GUI_TYPE_INT, true); moIntTotalCorrect.setIntegerSettings(SGuiUtils.getLabelName(jlTotalCorrect), SGuiConsts.GUI_TYPE_INT, true); moIntTotalIncorrect.setIntegerSettings(SGuiUtils.getLabelName(jlTotalIncorrect), SGuiConsts.GUI_TYPE_INT, true); moIntTotalStamp.setIntegerSettings(SGuiUtils.getLabelName(jlTotalStamps), SGuiConsts.GUI_TYPE_INT, true); moIntTotalConsumed.setIntegerSettings(SGuiUtils.getLabelName(jlTotalConsumed), SGuiConsts.GUI_TYPE_INT, true); moIntTotalAvailables.setIntegerSettings(SGuiUtils.getLabelName(jlTotalAvailables), SGuiConsts.GUI_TYPE_INT, true); moFields.addField(moIntTotalToProcess); moFields.addField(moIntTotalProcess); moFields.addField(moIntTotalCorrect); moFields.addField(moIntTotalIncorrect); moFields.addField(moIntTotalStamp); moFields.addField(moIntTotalConsumed); moFields.addField(moIntTotalAvailables); moFields.setFormButton(jbSave); } private void process() throws Exception { miClient.getFrame().setCursor(new Cursor(Cursor.WAIT_CURSOR)); if (manPayrollReceiptsId != null) { processPayroll(); } else if (maCfds != null) { processCfd(); } } public void processPayroll() { int number = 0; int cfdsProcessed = 0; int cfdsCorrect = 0; int cfdsIncorrect = 0; String detailMessage = ""; SDbPayrollReceiptIssue receiptIssue = null; if (manPayrollReceiptsId != null) { receiptIssue = new SDbPayrollReceiptIssue(); for (int[] key : manPayrollReceiptsId) { cfdsProcessed ++; try { switch (mnFormSubtype) { case SCfdConsts.PROC_REQ_STAMP: receiptIssue.read(miClient.getSession(), new int[] { key[0], key[1], key[2] }); if (receiptIssue.getPkIssueId() != SLibConsts.UNDEFINED) { number = SHrsUtils.getPayrollReceiptNextNumber(miClient.getSession(), receiptIssue.getNumberSeries()); if (receiptIssue.getNumber() == SLibConsts.UNDEFINED) { receiptIssue.saveField(miClient.getSession().getStatement(), new int[] { key[0], key[1], key[2] }, SDbPayrollReceiptIssue.FIELD_NUMBER, number); } } SHrsCfdUtils.computeSignCfdi(miClient.getSession(), new int[] { key[0], key[1], key[2] }); detailMessage += (receiptIssue.getNumberSeries().length() > 0 ? receiptIssue.getNumberSeries() + "-" : "") + number + " Timbrado" + (miClient.getSessionXXX().getParamsCompany().getIsCfdiSendingAutomaticHrs() ? " y enviado.\n" : ".\n"); cfdsCorrect ++; break; } } catch(Exception e) { detailMessage += "NOM-" + number + " " + e.getMessage() + "\n"; cfdsIncorrect++; } if (mnTotalStamps > 0) { updateForm(cfdsProcessed, cfdsCorrect, cfdsIncorrect, detailMessage, mnTotalStamps); } else { updateForm(cfdsProcessed, cfdsCorrect, cfdsIncorrect, detailMessage); } update(getGraphics()); jScrollPane1.getVerticalScrollBar().setValue(jScrollPane1.getVerticalScrollBar().getMaximum()); } miClient.getFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } public void processCfd() throws Exception { int cfdsProcessed = 0; int cfdsCorrect = 0; int cfdsIncorrect = 0; SDataFormerPayrollEmp payrollEmp = null; SDbPayrollReceipt payrollReceipt = null; SDbPayrollReceiptIssue payrollReceiptIssue = null; SDataDps dps = null; String detailMessage = ""; String numberSeries = ""; String number = ""; Print print = null; String sSql = ""; ResultSet resultSet = null; moIntTotalToProcess.setValue(maCfds.size()); if (maCfds != null) { for(SDataCfd cfd : maCfds) { cfdsProcessed++; switch (cfd.getFkCfdTypeId()) { case SCfdConsts.CFD_TYPE_DPS: dps = (SDataDps) SDataUtilities.readRegistry(miClient, SDataConstants.TRN_DPS, new int[] { cfd.getFkDpsYearId_n(), cfd.getFkDpsDocId_n() }, SLibConstants.EXEC_MODE_SILENT); numberSeries = dps.getNumberSeries(); number = dps.getNumber(); break; case SCfdConsts.CFD_TYPE_PAYROLL: switch (mnSubtypeCfd) { case SCfdConsts.CFDI_PAYROLL_VER_OLD: payrollEmp = (SDataFormerPayrollEmp) SDataUtilities.readRegistry(miClient, SDataConstants.HRS_FORMER_PAYR_EMP, new int[] { cfd.getFkPayrollPayrollId_n(), cfd.getFkPayrollEmployeeId_n() }, SLibConstants.EXEC_MODE_SILENT); numberSeries = payrollEmp.getNumberSeries(); number = "" + payrollEmp.getNumber(); break; case SCfdConsts.CFDI_PAYROLL_VER_CUR: /* payrollReceipt = new SDbPayrollReceipt(); payrollReceipt.read(miClient.getSession(), new int[] { cfd.getFkPayrollReceiptPayrollId_n(), cfd.getFkPayrollReceiptEmployeeId_n() }); if (payrollReceipt.getPayrollReceiptIssues() != null) { numberSeries = payrollReceipt.getPayrollReceiptIssues().getNumberSeries(); number = "" + payrollReceipt.getPayrollReceiptIssues().getNumber(); } */ // Read Issue last: sSql = "SELECT id_iss " + "FROM " + SModConsts.TablesMap.get(SModConsts.HRS_PAY_RCP_ISS) + " " + "WHERE id_pay = " + cfd.getFkPayrollReceiptPayrollId_n() + " AND id_emp = " + cfd.getFkPayrollReceiptEmployeeId_n() + " " + "ORDER BY id_iss DESC LIMIT 1"; resultSet = miClient.getSession().getDatabase().getConnection().createStatement().executeQuery(sSql); if (resultSet.next()) { payrollReceiptIssue = new SDbPayrollReceiptIssue(); numberSeries = (String) payrollReceiptIssue.readField(miClient.getSession().getDatabase().getConnection().createStatement(), new int[] { cfd.getFkPayrollReceiptPayrollId_n(), cfd.getFkPayrollReceiptEmployeeId_n(), resultSet.getInt("id_iss") }, SDbPayrollReceiptIssue.FIELD_NUMBER_SERIES); number = "" + (int) payrollReceiptIssue.readField(miClient.getSession().getDatabase().getConnection().createStatement(), new int[] { cfd.getFkPayrollReceiptPayrollId_n(), cfd.getFkPayrollReceiptEmployeeId_n(), resultSet.getInt("id_iss") }, SDbPayrollReceiptIssue.FIELD_NUMBER); } break; default: throw new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN); } break; default: throw new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN); } try { switch (mnFormSubtype) { case SCfdConsts.PROC_REQ_STAMP: SCfdUtils.signCfdi(miClient, cfd, mnSubtypeCfd, false); detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " Timbrado.\n"; break; case SCfdConsts.PROC_REQ_ANNUL: SCfdUtils.cancelCfdi(miClient, cfd, mnSubtypeCfd, mtCancellationDate, mbValidateStamp, false); detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " Anulado.\n"; break; case SCfdConsts.PROC_PRT_DOC: SCfdUtils.printCfd(miClient, cfd.getFkCfdTypeId(), cfd, SDataConstantsPrint.PRINT_MODE_STREAM, mnNumCopies, mnSubtypeCfd, false); detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " Impreso.\n"; break; case SCfdConsts.PROC_PRT_ACK_ANNUL: SCfdUtils.printAcknowledgmentCancellationCfd(miClient, cfd, SDataConstantsPrint.PRINT_MODE_STREAM, mnSubtypeCfd); detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " Impreso.\n"; break; case SCfdConsts.PROC_SND_DOC: SCfdUtils.sendCfd(miClient, cfd.getFkCfdTypeId(), cfd, mnSubtypeCfd, false); detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " Enviado.\n"; break; case SCfdConsts.PROC_REQ_STAMP_AND_SND: if (miClient.getSessionXXX().getParamsCompany().getIsCfdiSendingAutomaticHrs()) { SCfdUtils.signAndSendCfdi(miClient, cfd, mnSubtypeCfd, false); } else { SCfdUtils.signCfdi(miClient, cfd, mnSubtypeCfd, false); } detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + "Timbrado" + (miClient.getSessionXXX().getParamsCompany().getIsCfdiSendingAutomaticHrs() ? " y enviado.\n" : ".\n"); break; case SCfdConsts.PROC_REQ_ANNUL_AND_SND: if (miClient.getSessionXXX().getParamsCompany().getIsCfdiSendingAutomaticHrs()) { SCfdUtils.cancelAndSendCfdi(miClient, cfd, mnSubtypeCfd, mtCancellationDate, mbValidateStamp, false); } else { SCfdUtils.cancelCfdi(miClient, cfd, mnSubtypeCfd, mtCancellationDate, mbValidateStamp, false); } detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " Anulado" + (miClient.getSessionXXX().getParamsCompany().getIsCfdiSendingAutomaticHrs() ? " y enviado.\n" : ".\n"); break; case SCfdConsts.PROC_REQ_VERIFY: SCfdUtils.verifyCfdi(miClient, cfd, mnSubtypeCfd); detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " Enviado.\n"; break; default: } cfdsCorrect++; } catch(Exception e) { detailMessage += (numberSeries.length() > 0 ? numberSeries + "-" : "") + number + " " + e.getMessage() + "\n"; cfdsIncorrect++; } if (mnTotalStamps > 0) { updateForm(cfdsProcessed, cfdsCorrect, cfdsIncorrect, detailMessage, mnTotalStamps); } else { updateForm(cfdsProcessed, cfdsCorrect, cfdsIncorrect, detailMessage); } update(getGraphics()); jScrollPane1.getVerticalScrollBar().setValue(jScrollPane1.getVerticalScrollBar().getMaximum()); } miClient.getFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } public synchronized SGuiSession getSession() { SGuiSession session = new SGuiSession((SGuiClient) miClient); session.setUser(miClient.getSessionXXX().getUser()); // XXX this must be replaced session.setSystemDate(miClient.getSessionXXX().getSystemDate()); session.setCurrentDate(miClient.getSessionXXX().getWorkingDate()); session.setUserTs(miClient.getSessionXXX().getSystemDate()); session.setDatabase(miClient.getSession().getDatabase()); return session; } private void updateForm(final int totalProcess, final int totalCorrect, final int totalIncorrect, final String message, final int totalStamp) { moIntTotalProcess.setValue(totalProcess); moIntTotalCorrect.setValue(totalCorrect); moIntTotalIncorrect.setValue(totalIncorrect); moIntTotalStamp.setValue(totalStamp); moIntTotalConsumed.setValue(totalCorrect); moIntTotalAvailables.setValue(totalStamp - totalCorrect); jtaMessage.setText(message); } public void updateForm(final int totalProcess, final int totalCorrect, final int totalIncorrect, final String message) { moIntTotalProcess.setValue(totalProcess); moIntTotalCorrect.setValue(totalCorrect); moIntTotalIncorrect.setValue(totalIncorrect); moIntTotalStamp.setValue(0); moIntTotalConsumed.setValue(0); moIntTotalAvailables.setValue(0); jtaMessage.setText(message); } public void setFormParams(final SClientInterface client, final ArrayList<SDataCfd> cfds, final ArrayList<int[]> payrollReceipts, final int totalStamp, Date cancellationDate, final boolean validateStamp, final int subtypeCfd) { mbFirstTime = true; miClient = client; maCfds = cfds; manPayrollReceiptsId = payrollReceipts; mnTotalStamps = totalStamp; mtCancellationDate = cancellationDate; mbValidateStamp = validateStamp; mnSubtypeCfd = subtypeCfd; } public void setNumberCopies(final int numCopies) { mnNumCopies = numCopies; } @Override public void addAllListeners() { } @Override public void removeAllListeners() { } @Override public void reloadCatalogues() { } @Override public void setRegistry(SDbRegistry registry) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @Override public SDbRegistry getRegistry() throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @Override public SGuiValidation validateForm() { SGuiValidation validation = moFields.validateFields(); return validation; } }
Minor changes update: - Update form for calculation amount net and gross. - New report, period assets by employees. - New report, pending vacation. - New benefit of the number of copies in print payroll CFDI. - New benefit CFDI system of payroll in print. - Bug fixr in calculating the amount to withhold a loan. - Bug fix in the payment application from a layout.
src/erp/cfd/SDialogResult.java
Minor changes update: - Update form for calculation amount net and gross. - New report, period assets by employees. - New report, pending vacation. - New benefit of the number of copies in print payroll CFDI. - New benefit CFDI system of payroll in print. - Bug fixr in calculating the amount to withhold a loan. - Bug fix in the payment application from a layout.
<ide><path>rc/erp/cfd/SDialogResult.java <ide> import erp.mtrn.data.SCfdUtils; <ide> import erp.mtrn.data.SDataCfd; <ide> import erp.mtrn.data.SDataDps; <del>import erp.print.Print; <ide> import erp.print.SDataConstantsPrint; <ide> import java.awt.Cursor; <ide> import java.sql.ResultSet; <ide> String detailMessage = ""; <ide> String numberSeries = ""; <ide> String number = ""; <del> Print print = null; <ide> String sSql = ""; <ide> ResultSet resultSet = null; <ide>
JavaScript
mit
d523a6daf3540cc869cb39cd11b5471dec075f9c
0
mantoni/phantomic,mantoni/phantomic,mantoni/phantomic
'use strict'; var through = require('through'); var convert = require('convert-source-map'); var sourceMap = require('source-map'); var spawn = require('child_process').spawn; var exec = require('child_process').exec; var http = require('http'); var fs = require('fs'); var stackRE = /http\:\/\/localhost\:[0-9]+\/js\/bundle\:([0-9]+)/g; var inspector = 'http://localhost:9000/webkit/inspector/inspector.html?page=2'; function stackMapper(mapper) { var buf = ''; return through(function (data) { if (data) { buf += data.toString(); var p = buf.lastIndexOf('\n'); if (p !== -1) { var str = buf.substring(0, p + 1).replace(stackRE, function (m, nr) { /*jslint unparam: true*/ if (nr < 1) { return '?'; } var mapped = mapper.originalPositionFor({ line : Number(nr), column : 0 }); return mapped.source + ':' + mapped.line; }); this.queue(str); buf = buf.substring(p + 1); } if (buf.length > 3 && !/^\s+at /.test(buf)) { this.queue(buf); buf = ''; } } }); } function httpServer(port, js, callback) { var server = http.createServer(function (req, res) { var url = req.url; var p = url.indexOf('?'); if (p !== -1) { url = url.substring(0, p); } if (url === '/') { res.writeHead(200); fs.createReadStream(__dirname + '/page.html').pipe(res); } else if (url === '/js/bundle') { res.writeHead(200); res.write(js); res.end(); } else if (url === '/js/es5-shim') { res.writeHead(200); fs.createReadStream(require.resolve('es5-shim/es5-shim')).pipe(res); } else { res.writeHead(404); res.end(); } }); server.listen(port || 0, function (err) { callback(err, server.address().port); }); } function launchPhantom(output, options, callback) { var args = [__dirname + '/runner.js']; if (options.debug) { args.unshift('--remote-debugger-autorun=yes'); args.unshift('--remote-debugger-port=9000'); } var exitCode; var ended = 0; var onEnd = function () { if (++ended === 3) { output.queue(null); process.nextTick(function () { callback(exitCode); }); } }; var phantomjs = spawn('phantomjs', args, { env: { PATH: process.env.PATH, PHANTOMIC_PORT: options.port, PHANTOMIC_DEBUG: options.debug ? '1' : '', PHANTOMIC_BROUT: options.brout ? '1' : '' } }); phantomjs.stdout.pipe(output); phantomjs.stderr.on('data', function (data) { if (data.toString() === 'PHANTOMIC_DEBUG') { var cmd; if (process.platform === 'darwin') { cmd = 'open'; } else if (process.platform === 'win32') { cmd = 'start ""'; } if (cmd) { exec(cmd + ' ' + inspector); } else { process.stderr.write('\nPlease open ' + inspector + '\n'); } } else { output.queue(data); } }); phantomjs.stdout.on('end', onEnd); phantomjs.stderr.on('end', onEnd); phantomjs.on('exit', function (code) { exitCode = code; onEnd(); }); } module.exports = function (input, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } var output = through(); var js = ''; input.on('data', function (d) { js += d; }); input.on('end', function () { var map = convert.fromSource(js); if (map) { map = map.toObject(); delete map.sourcesContent; var mapper = new sourceMap.SourceMapConsumer(map); js = convert.removeComments(js); var sm = stackMapper(mapper); sm.pipe(output); output = sm; } httpServer(options.port, js, function (err, port) { if (err) { process.stderr.write('Server failed: ' + err.toString() + '\n'); callback(1); } else { options.port = port; launchPhantom(output, options, callback); } }); }); return output; };
lib/phantomic.js
'use strict'; var through = require('through'); var convert = require('convert-source-map'); var sourceMap = require('source-map'); var spawn = require('child_process').spawn; var exec = require('child_process').exec; var http = require('http'); var fs = require('fs'); var stackRE = /http\:\/\/localhost\:[0-9]+\/js\/bundle\:([0-9]+)/g; var inspector = 'http://localhost:9000/webkit/inspector/inspector.html?page=2'; function stackMapper(mapper) { var buf = ''; return through(function (data) { if (data) { buf += data.toString(); var p = buf.lastIndexOf('\n'); if (p !== -1) { var str = buf.substring(0, p + 1).replace(stackRE, function (m, nr) { /*jslint unparam: true*/ if (nr < 1) { return '?'; } var mapped = mapper.originalPositionFor({ line : Number(nr), column : 0 }); return mapped.source + ':' + mapped.line; }); this.queue(str); buf = buf.substring(p + 1); } if (buf.length > 3 && !/^\s+at /.test(buf)) { this.queue(buf); buf = ''; } } }); } function httpServer(port, js, callback) { var server = http.createServer(function (req, res) { var url = req.url; var p = url.indexOf('?'); if (p !== -1) { url = url.substring(0, p); } if (url === '/') { res.writeHead(200); fs.createReadStream(__dirname + '/page.html').pipe(res); } else if (url === '/js/bundle') { res.writeHead(200); res.write(js); res.end(); } else if (url === '/js/es5-shim') { res.writeHead(200); fs.createReadStream(require.resolve('es5-shim/es5-shim')).pipe(res); } else { res.writeHead(404); res.end(); } }); server.listen(port || 0, function (err) { callback(err, server.address().port); }); } function launchPhantom(output, options, callback) { var args = [__dirname + '/runner.js']; if (options.debug) { args.unshift('--remote-debugger-autorun=yes'); args.unshift('--remote-debugger-port=9000'); } var phantomjs = spawn('phantomjs', args, { env: { PATH: process.env.PATH, PHANTOMIC_PORT: options.port, PHANTOMIC_DEBUG: options.debug ? '1' : '', PHANTOMIC_BROUT: options.brout ? '1' : '' } }); phantomjs.stdout.pipe(output); phantomjs.stderr.on('data', function (data) { if (data.toString() === 'PHANTOMIC_DEBUG') { var cmd; if (process.platform === 'darwin') { cmd = 'open'; } else if (process.platform === 'win32') { cmd = 'start ""'; } if (cmd) { exec(cmd + ' ' + inspector); } else { process.stderr.write('\nPlease open ' + inspector + '\n'); } } else { output.queue(data); } }); phantomjs.on('exit', function (code) { output.queue(null); process.nextTick(function () { callback(code); }); }); } module.exports = function (input, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } var output = through(); var js = ''; input.on('data', function (d) { js += d; }); input.on('end', function () { var map = convert.fromSource(js); if (map) { map = map.toObject(); delete map.sourcesContent; var mapper = new sourceMap.SourceMapConsumer(map); js = convert.removeComments(js); var sm = stackMapper(mapper); sm.pipe(output); output = sm; } httpServer(options.port, js, function (err, port) { if (err) { process.stderr.write('Server failed: ' + err.toString() + '\n'); callback(1); } else { options.port = port; launchPhantom(output, options, callback); } }); }); return output; };
Wait for phantomjs output streams to end
lib/phantomic.js
Wait for phantomjs output streams to end
<ide><path>ib/phantomic.js <ide> args.unshift('--remote-debugger-autorun=yes'); <ide> args.unshift('--remote-debugger-port=9000'); <ide> } <add> var exitCode; <add> var ended = 0; <add> var onEnd = function () { <add> if (++ended === 3) { <add> output.queue(null); <add> process.nextTick(function () { <add> callback(exitCode); <add> }); <add> } <add> }; <ide> var phantomjs = spawn('phantomjs', args, { <ide> env: { <ide> PATH: process.env.PATH, <ide> output.queue(data); <ide> } <ide> }); <add> phantomjs.stdout.on('end', onEnd); <add> phantomjs.stderr.on('end', onEnd); <ide> phantomjs.on('exit', function (code) { <del> output.queue(null); <del> process.nextTick(function () { <del> callback(code); <del> }); <add> exitCode = code; <add> onEnd(); <ide> }); <ide> } <ide>
JavaScript
mit
07323f65173280498ee2d216be50792d6681b9a9
0
ft-interactive/uk-political-parties
'use strict'; var parties = require('./index.js'); function check(n){ if(n){ process.stdout.write('.'); return 0; }else{ process.stdout.write('X'); return 1; } } function report(fails){ console.log('\n\n:('); for(var t in fails){ if(fails[t]>0){ console.log(t + '\t\t: ' + fails[t] + ' fail(s)'); } } } var tests = [ { name:'Full Names', assertions:[ (parties.fullName('lab') === 'Labour'), (parties.fullName('c') === 'Conservative'), (parties.fullName('ukip') === 'Ukip') ] }, { name:'Colours', assertions:[ (parties.colour('lab') === '#e25050'), (parties.colour('c') === '#6da8e1'), (parties.colour('pc') === '#99d2d0') ] }, { name:'Populous To Full Name', assertions:[ (parties.populousToFullName('Tory') === 'Conservative'), (parties.populousToFullName('Labour') === 'Labour'), (parties.populousToFullName('UKIP') === 'Ukip') ] }, { name:'Full Name To Code', assertions:[ (parties.fullNameToCode('Conservative') === 'c'), (parties.fullNameToCode('Labour') === 'lab'), (parties.fullNameToCode('Ukip') === 'ukip') ] } ]; var pass = true; var fails = {}; tests.forEach(function(t){ console.log('Test : ', t.name); fails[t.name] = 0; pass = t.assertions.reduce(function(value, n){ fails[t.name] += check(n); return (value && n); }, pass); console.log(); }); if(pass){ console.log('All OK!'); process.exit(0); } report(fails); process.exit(1);
test.js
'use strict'; var parties = require('./index.js'); function check(n){ if(n){ process.stdout.write('.'); return 0; }else{ process.stdout.write('X'); return 1; } } function report(fails){ console.log('\n\n:('); for(var t in fails){ if(fails[t]>0){ console.log(t + '\t\t: ' + fails[t] + ' fail(s)'); } } } var tests = [ { name:'Full Names', assertions:[ (parties.fullName('lab') === 'Labour'), (parties.fullName('c') === 'Conservatives'), (parties.fullName('ukip') === 'Ukip') ] }, { name:'Colours', assertions:[ (parties.colour('lab') === '#e25050'), (parties.colour('c') === '#6da8e1'), (parties.colour('pc') === '#99d2d0') ] }, { name:'Populous To Full Name', assertions:[ (parties.populousToFullName('Tory') === 'Conservatives'), (parties.populousToFullName('Labour') === 'Labour'), (parties.populousToFullName('UKIP') === 'Ukip') ] }, { name:'Full Name To Code', assertions:[ (parties.fullNameToCode('Conservatives') === 'c'), (parties.fullNameToCode('Labour') === 'lab'), (parties.fullNameToCode('Ukip') === 'ukip') ] } ]; var pass = true; var fails = {}; tests.forEach(function(t){ console.log('Test : ', t.name); fails[t.name] = 0; pass = t.assertions.reduce(function(value, n){ fails[t.name] += check(n); return (value && n); }, pass); console.log(); }); if(pass){ console.log('All OK!'); process.exit(0); } report(fails); process.exit(1);
update tests
test.js
update tests
<ide><path>est.js <ide> name:'Full Names', <ide> assertions:[ <ide> (parties.fullName('lab') === 'Labour'), <del> (parties.fullName('c') === 'Conservatives'), <add> (parties.fullName('c') === 'Conservative'), <ide> (parties.fullName('ukip') === 'Ukip') <ide> ] <ide> }, <ide> { <ide> name:'Populous To Full Name', <ide> assertions:[ <del> (parties.populousToFullName('Tory') === 'Conservatives'), <add> (parties.populousToFullName('Tory') === 'Conservative'), <ide> (parties.populousToFullName('Labour') === 'Labour'), <ide> (parties.populousToFullName('UKIP') === 'Ukip') <ide> ] <ide> { <ide> name:'Full Name To Code', <ide> assertions:[ <del> (parties.fullNameToCode('Conservatives') === 'c'), <add> (parties.fullNameToCode('Conservative') === 'c'), <ide> (parties.fullNameToCode('Labour') === 'lab'), <ide> (parties.fullNameToCode('Ukip') === 'ukip') <ide> ]
Java
apache-2.0
b1dcac0c689b3ce6d71e7444e791cb86bacc1e65
0
babble/babble,babble/babble,babble/babble,babble/babble,babble/babble,babble/babble
// TimeConstants.java /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ed.util; public class TimeConstants { public static final long MS_MILLISECOND = 1; public static final long MS_SECOND = 1000; public static final long MS_MINUTE = MS_SECOND * 60; public static final long MS_HOUR = MS_MINUTE * 60; public static final long MS_DAY = MS_HOUR * 24; public static final long MS_WEEK = MS_DAY * 7; public static final long MS_MONTH = MS_WEEK * 4; public static final long MS_YEAR = MS_DAY * 365; public static final long S_SECOND = 1; public static final long S_MINUTE = 60 * S_SECOND; public static final long S_HOUR = 60 * S_MINUTE; public static final long S_DAY = 24 * S_HOUR; public static final long S_WEEK = 7 * S_DAY; public static final long S_MONTH = 30 * S_DAY; public static final long S_YEAR = S_DAY * 365; }
src/main/ed/util/TimeConstants.java
// TimeConstants.java package ed.util; public class TimeConstants { public static final long MS_MILLISECOND = 1; public static final long MS_SECOND = 1000; public static final long MS_MINUTE = MS_SECOND * 60; public static final long MS_HOUR = MS_MINUTE * 60; public static final long MS_DAY = MS_HOUR * 24; public static final long MS_WEEK = MS_DAY * 7; public static final long MS_MONTH = MS_WEEK * 4; public static final long MS_YEAR = MS_DAY * 365; public static final long S_SECOND = 1; public static final long S_MINUTE = 60 * S_SECOND; public static final long S_HOUR = 60 * S_MINUTE; public static final long S_DAY = 24 * S_HOUR; public static final long S_WEEK = 7 * S_DAY; public static final long S_MONTH = 30 * S_DAY; public static final long S_YEAR = S_DAY * 365; }
license
src/main/ed/util/TimeConstants.java
license
<ide><path>rc/main/ed/util/TimeConstants.java <ide> // TimeConstants.java <add> <add>/** <add>* Copyright (C) 2008 10gen Inc. <add>* <add>* This program is free software: you can redistribute it and/or modify <add>* it under the terms of the GNU Affero General Public License, version 3, <add>* as published by the Free Software Foundation. <add>* <add>* This program is distributed in the hope that it will be useful, <add>* but WITHOUT ANY WARRANTY; without even the implied warranty of <add>* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the <add>* GNU Affero General Public License for more details. <add>* <add>* You should have received a copy of the GNU Affero General Public License <add>* along with this program. If not, see <http://www.gnu.org/licenses/>. <add>*/ <ide> <ide> package ed.util; <ide> <ide> public static final long S_MONTH = 30 * S_DAY; <ide> public static final long S_YEAR = S_DAY * 365; <ide> } <del>
Java
apache-2.0
a9250fe5c0c3d140619609f8444b73dbd92e4eb2
0
qiu-ming/coolWeather
package com.coolweather.app.activity; import java.util.ArrayList; import java.util.List; import com.coolweather.app.R; import com.coolweather.app.model.City; import com.coolweather.app.model.CoolWeatherDB; import com.coolweather.app.model.County; import com.coolweather.app.model.Province; import com.coolweather.app.util.HttpCallbackListener; import com.coolweather.app.util.HttpUtil; import com.coolweather.app.util.Utility; import android.view.*; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.text.TextUtils; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class ChooseAreaActivity extends Activity { public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY = 1; public static final int LEVEL_COUNTY = 2; private ProgressDialog progressDialog; private TextView titleText; private ListView listView; private ArrayAdapter<String> adapter; private CoolWeatherDB coolWeatherDB; private List<String> dataList = new ArrayList<String>(); /** * ʡб */ private List<Province> provinceList; /** * б */ private List<City> cityList; /** * б */ private List<County> countyList; /** * ѡеʡ */ private Province selectedProvince; /** * ѡеij */ private City selectedCity; /** * ǰѡеļ */ private int currentLevel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.choose_area); listView = (ListView) findViewById(R.id.list_view); titleText = (TextView) findViewById(R.id.title_text); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList); listView.setAdapter(adapter); coolWeatherDB = CoolWeatherDB.getInstance(this); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) { if (currentLevel == LEVEL_PROVINCE) { selectedProvince = provinceList.get(index); queryCities(); } else if (currentLevel == LEVEL_CITY) { selectedCity = cityList.get(index); queryCounties(); } } }); queryProvinces(); // ʡ } /** * ѯȫеʡȴݿѯûвѯȥϲѯ */ private void queryProvinces() { provinceList = coolWeatherDB.loadProvinces(); if (provinceList.size() > 0) { dataList.clear(); for (Province province : provinceList) { dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText("й"); currentLevel = LEVEL_PROVINCE; } else { queryFromServer(null, "province"); } } /** * ѯѡʡеУȴݿѯûвѯȥϲѯ */ private void queryCities() { cityList = coolWeatherDB.loadCities(selectedProvince.getId()); if (cityList.size() > 0) { dataList.clear(); for (City city : cityList) { dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText(selectedProvince.getProvinceName()); currentLevel = LEVEL_CITY; } else { queryFromServer(selectedProvince.getProvinceCode(), "city"); } } /** * ѯѡеأȴݿѯûвѯȥϲѯ */ private void queryCounties() { countyList = coolWeatherDB.loadCounties(selectedCity.getId()); if (countyList.size() > 0) { dataList.clear(); for (County county : countyList) { dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText(selectedCity.getCityName()); currentLevel = LEVEL_COUNTY; } else { queryFromServer(selectedCity.getCityCode(), "county"); } } /** * ݴĴźʹӷϲѯʡݡ */ private void queryFromServer(final String code, final String type) { String address; if (!TextUtils.isEmpty(code)) { address = "http://www.weather.com.cn/data/list3/city" + code + ".xml"; } else { address = "http://www.weather.com.cn/data/list3/city.xml"; } showProgressDialog(); HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(String response) { boolean result = false; if ("province".equals(type)) { result = Utility.handleProvincesResponse(coolWeatherDB, response); } else if ("city".equals(type)) { result = Utility.handleCitiesResponse(coolWeatherDB, response, selectedProvince.getId()); } else if ("county".equals(type)) { result = Utility.handleCountiesResponse(coolWeatherDB, response, selectedCity.getId()); } if (result) { // ͨrunOnUiThread()ص̴߳߼ runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); if ("province".equals(type)) { queryProvinces(); } else if ("city".equals(type)) { queryCities(); } else if ("county".equals(type)) { queryCounties(); } } }); } } @Override public void onError(Exception e) { // ͨrunOnUiThread()ص̴߳߼ runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(ChooseAreaActivity.this, "ʧ", Toast.LENGTH_SHORT).show(); } }); } }); } /** * ʾȶԻ */ private void showProgressDialog() { if (progressDialog == null) { progressDialog = new ProgressDialog(this); progressDialog.setMessage("ڼ..."); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } /** * رսȶԻ */ private void closeProgressDialog() { if (progressDialog != null) { progressDialog.dismiss(); } } /** * BackݵǰļжϣʱӦ÷бʡбֱ˳ һд Android 506 */ @Override public void onBackPressed() { if (currentLevel == LEVEL_COUNTY) { queryCities(); } else if (currentLevel == LEVEL_CITY) { queryProvinces(); } else { finish(); } } }
src/com/coolweather/app/activity/ChooseAreaActivity.java
package com.coolweather.app.activity; import java.util.ArrayList; import java.util.List; import com.coolweather.app.R; import com.coolweather.app.model.City; import com.coolweather.app.model.CoolWeatherDB; import com.coolweather.app.model.County; import com.coolweather.app.model.Province; import com.coolweather.app.util.HttpCallbackListener; import com.coolweather.app.util.HttpUtil; import com.coolweather.app.util.Utility; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class ChooseAreaActivity extends Activity { public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY = 1; public static final int LEVEL_COUNTY = 2; private ProgressDialog progressDialog; private TextView titleText; private ListView listView; private ArrayAdapter<String> adapter; private CoolWeatherDB coolWeatherDB; private List<String> dataList = new ArrayList<String>(); /** * ʡб */ private List<Province> provinceList; /** * б */ private List<City> cityList; /** * б */ private List<County> countyList; /** * ѡеʡ */ private Province selectedProvince; /** * ѡеij */ private City selectedCity; /** * ǰѡеļ */ private int currentLevel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.choose_area); listView = (ListView) findViewById(R.id.list_view); titleText = (TextView) findViewById(R.id.title_text); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList); listView.setAdapter(adapter); coolWeatherDB = CoolWeatherDB.getInstance(this); listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick1(AdapterView<?> arg0, View view, int index, long arg3) { if (currentLevel == LEVEL_PROVINCE) { selectedProvince = provinceList.get(index); queryCities(); } else if (currentLevel == LEVEL_CITY) { selectedCity = cityList.get(index); queryCounties(); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub } }); queryProvinces(); // ʡ } /** * ѯȫеʡȴݿѯûвѯȥϲѯ */ private void queryProvinces() { provinceList = coolWeatherDB.loadProvinces(); if (provinceList.size() > 0) { dataList.clear(); for (Province province : provinceList) { dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText("й"); currentLevel = LEVEL_PROVINCE; } else { queryFromServer(null, "province"); } } /** * ѯѡʡеУȴݿѯûвѯȥϲѯ */ private void queryCities() { cityList = coolWeatherDB.loadCities(selectedProvince.getId()); if (cityList.size() > 0) { dataList.clear(); for (City city : cityList) { dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText(selectedProvince.getProvinceName()); currentLevel = LEVEL_CITY; } else { queryFromServer(selectedProvince.getProvinceCode(), "city"); } } /** * ѯѡеأȴݿѯûвѯȥϲѯ */ private void queryCounties() { countyList = coolWeatherDB.loadCounties(selectedCity.getId()); if (countyList.size() > 0) { dataList.clear(); for (County county : countyList) { dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); titleText.setText(selectedCity.getCityName()); currentLevel = LEVEL_COUNTY; } else { queryFromServer(selectedCity.getCityCode(), "county"); } } /** * ݴĴźʹӷϲѯʡݡ */ private void queryFromServer(final String code, final String type) { String address; if (!TextUtils.isEmpty(code)) { address = "http://www.weather.com.cn/data/list3/city" + code + ".xml"; } else { address = "http://www.weather.com.cn/data/list3/city.xml"; } showProgressDialog(); HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(String response) { boolean result = false; if ("province".equals(type)) { result = Utility.handleProvincesResponse(coolWeatherDB, response); } else if ("city".equals(type)) { result = Utility.handleCitiesResponse(coolWeatherDB, response, selectedProvince.getId()); } else if ("county".equals(type)) { result = Utility.handleCountiesResponse(coolWeatherDB, response, selectedCity.getId()); } if (result) { // ͨrunOnUiThread()ص̴߳߼ runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); if ("province".equals(type)) { queryProvinces(); } else if ("city".equals(type)) { queryCities(); } else if ("county".equals(type)) { queryCounties(); } } }); } } @Override public void onError(Exception e) { // ͨrunOnUiThread()ص̴߳߼ runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(ChooseAreaActivity.this, "ʧ", Toast.LENGTH_SHORT).show(); } }); } }); } /** * ʾȶԻ */ private void showProgressDialog() { if (progressDialog == null) { progressDialog = new ProgressDialog(this); progressDialog.setMessage("ڼ..."); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } /** * رսȶԻ */ private void closeProgressDialog() { if (progressDialog != null) { progressDialog.dismiss(); } } /** * BackݵǰļжϣʱӦ÷бʡбֱ˳ һд Android 506 */ @Override public void onBackPressed() { if (currentLevel == LEVEL_COUNTY) { queryCities(); } else if (currentLevel == LEVEL_CITY) { queryProvinces(); } else { finish(); } } }
完成遍历省市县三级列表的功能。
src/com/coolweather/app/activity/ChooseAreaActivity.java
完成遍历省市县三级列表的功能。
<ide><path>rc/com/coolweather/app/activity/ChooseAreaActivity.java <ide> import com.coolweather.app.util.HttpCallbackListener; <ide> import com.coolweather.app.util.HttpUtil; <ide> import com.coolweather.app.util.Utility; <del> <add>import android.view.*; <ide> import android.app.Activity; <ide> import android.app.ProgressDialog; <ide> import android.os.Bundle; <ide> import android.text.TextUtils; <del>import android.view.View; <ide> import android.view.Window; <ide> import android.widget.AdapterView; <ide> import android.widget.AdapterView.OnItemClickListener; <ide> listView.setAdapter(adapter); <ide> coolWeatherDB = CoolWeatherDB.getInstance(this); <ide> listView.setOnItemClickListener(new OnItemClickListener() { <del>public void onItemClick1(AdapterView<?> arg0, View view, int index, <add>@Override <add>public void onItemClick(AdapterView<?> arg0, View view, int index, <ide> long arg3) { <ide> if (currentLevel == LEVEL_PROVINCE) { <ide> selectedProvince = provinceList.get(index); <ide> selectedCity = cityList.get(index); <ide> queryCounties(); <ide> } <del>} <del> <del>@Override <del>public void onItemClick(AdapterView<?> parent, View view, int position, long id) { <del> // TODO Auto-generated method stub <del> <ide> } <ide> }); <ide> queryProvinces(); // ʡ